emrModule.controller("EmrCustomTemplateCtrl", ["$log", "$q", "patientDocumentSvc", "$scope", "host", "$modalInstance", "aresNotification", "appointmentSvc", function(n, t, i, r, u, f, e, o) {
    "use strict";
    var h = function() {
            f.close()
        },
        c = function() {
            r.document.appointmentId > 0 ? s() : l().then(s)
        },
        l = function() {
            var n = t.defer(),
                i = _.find(r.historyAppts, {
                    id: -2
                });
            return i ? (i.doctorId = r.currentDoctor.id, o.createAppointment(i).success(function(t) {
                r.document.appointmentId = t.id;
                n.resolve(!0)
            })) : n.resolve(!0), n.promise
        },
        s = function() {
            i.savePatientDocument(r.document).success(function(n) {
                e.success("操作成功！");
                f.close(n)
            })
        },
        a = function() {
            i.getDocTemplateList({
                isWithFields: !1,
                templateType: 2
            }).success(function(n) {
                r.templates = n
            })
        };
    (function() {
        r.patientId = u.patientId;
        r.cancel = h;
        r.save = c;
        a()
    })()
}]);
emrModule.controller("EmrWorkflowCtrl", ["$log", "$q", "$filter", "$timeout", "$scope", "enums", "$modalInstance", "host", "dataDicSvc", "systemConfigUtil", "officeOptionSvc", function(n, t, i, r, u, f, e, o, s, h, c) {
    "use strict";
    var l = function() {
            e.dismiss()
        },
        a = function(n) {
            var t, i;
            n.name || n.content && (t = n.content.split("："), t.length > 0 && (n.name = t[0] + "：", n.content = t[1]));
            n.archive = n.archive ? n.archive : "";
            i = s.officeDic.getItemSync(n.OfficeId);
            i && (n.officeName = i.abbreviation)
        },
        v = function() {
            h.getConfigValue(h.configKeys.AllowToothFDI).then(function(n) {
                u.allowToothFDI = n ? n : !1
            })
        },
        y = function() {
            h.getConfigValue(h.configKeys.AllowEditToothFDI).then(function(n) {
                u.allowEditTooth = n ? n : !1
            })
        },
        p = function() {
            c.getOfficeOption(c.optionKeys.IsEmrCustomTemplateEnabled).then(function(n) {
                n == "1" && (u.isShowCustomBtn = !0, u.isEmrCustomTemplateEnabled = !0)
            })
        };
    (function() {
        u.medicalRecord = o.medicalRecord;
        u.clean = l;
        a(u.medicalRecord);
        v();
        y();
        p()
    })()
}]);
emrModule.controller("EMRNewTemplateSaveController", ["$log", "$scope", "$modalInstance", "host", function(n, t, i, r) {
    "use strict";
    t.cancel = function() {
            i.dismiss("cancel")
        },
        function() {
            t.templateTreeControl = r.templateTreeControl;
            t.currentEMRTemplate = r.currentEMRTemplate;
            t.currentDiseaseId = r.currentDiseaseId;
            t.currentEMRTemplateDiseaseBreadcrumb = ""
        }()
}]);
emrModule.controller("PatientNewEmrEditCtrl", ["$scope", "$rootScope", "$timeout", "$q", "$log", "$stateParams", "$state", "$modal", "aresDialog", "constants", "appointmentSvc", "practiceSvc", "apptUtil", "enums", "loginContext", "permissionProvider", "patientSvc", "appNav", "dataDicSvc", "generalExamSvc", "officeSvc", "officeOptionSvc", "formatUtil", "aresNotification", "systemConfigUtil", "patientUtil", "aresTreeControlUtil", "workflowSvc", "systemConfigSvc", "eventAggregator", "chargeSvc", "providerUtil", "localCache", "emrUtil", "emrCustomizeEditUtil", "approvalUtil", function(n, t, i, r, u, f, e, o, s, h, c, l, a, v, y, p, w, b, k, d, g, nt, tt, it, rt, ut, ft, et, ot, st, ht, ct, lt, at, vt, yt) {
    "use strict";
    var ri = lt.getCache(lt.keys.IsAllowSynchronizationOption);
    n.currentEMRTemplate = {};
    var tr = function() {
            n.currentEMRTemplate = {
                templateName: "",
                Pinyin: "",
                diseaseId: null,
                chiefComplaint: n.currentMedicalRecord.chiefComplaint,
                history: n.currentMedicalRecord.history,
                pastHistory: n.currentMedicalRecord.pastHistory,
                oralCheck: ir(n.currentMedicalRecord),
                otherCheck: rr(n.currentMedicalRecord),
                diagnose: or(n.currentMedicalRecord),
                treatmentPlan: hr(n.currentMedicalRecord),
                treatmentAdvice: sr(n.currentMedicalRecord),
                treatment: ur(n.currentMedicalRecord),
                advice: n.currentMedicalRecord.advice,
                layoutTemplateCode: n.currentMedicalRecord.layoutTemplateCode,
                templateType: fr(n.currentMedicalRecord.layoutTemplateCode)
            };
            var t = o.open({
                animation: !0,
                backdrop: "static",
                template: "<patient-new-emr-template-save><\/patient-new-emr-template-save>",
                controller: "EMRNewTemplateSaveController",
                windowClass: "emrtemplatesave-dialog",
                size: "sm",
                resolve: {
                    host: function() {
                        return {
                            currentDiseaseId: n.currentDisease ? n.currentDisease.id : 0,
                            currentEMRTemplate: n.currentEMRTemplate,
                            templateTreeControl: n.templateTreeControl
                        }
                    }
                }
            });
            t.result.then(function() {}, function() {
                var t = n.currentMedicalRecord.layoutTemplateCode,
                    i = at.getTemplateTypeByCode(t);
                w.listEMRTemplates(i, t).success(function(t) {
                    n.emrTemplates = t;
                    ii(n.diseaseItems, n.emrTemplates)
                })
            })
        },
        ir = function(n) {
            var t, i, r;
            if (n && n.oralCheckRecordList) {
                for (t = "", i = 0; i < n.oralCheckRecordList.length; ++i) n.oralCheckRecordList[i].description && (t = t + n.oralCheckRecordList[i].description, r = n.oralCheckRecordList[i].description.slice(-1), r != "。" && (t = t + "。"));
                return t != "。" ? t : ""
            }
            return ""
        },
        rr = function(n) {
            var t, i, r;
            if (n && n.radiologyCheckRecordList) {
                for (t = "", i = 0; i < n.radiologyCheckRecordList.length; ++i) n.radiologyCheckRecordList[i].description && (t = t + n.radiologyCheckRecordList[i].description, r = n.radiologyCheckRecordList[i].description.slice(-1), r != "。" && (t = t + "。"));
                return t != "。" ? t : ""
            }
            return ""
        },
        ur = function(n) {
            var t, i, r;
            if (n && n.cureRecordList) {
                for (t = "", i = 0; i < n.cureRecordList.length; ++i) n.cureRecordList[i].cure && (t = t + n.cureRecordList[i].cure, r = n.cureRecordList[i].cure.slice(-1), r != "。" && (t = t + "。"));
                return t != "。" ? t : ""
            }
            return ""
        },
        fr = function(n) {
            return n === h.firstVisitTemplateCode ? v.VisitType.FirstVisit : n === h.secondVisitTemplateCode ? v.VisitType.ReturnVisit : v.VisitType.Customized
        },
        er = function() {
            var t = r.defer();
            return l.getProvider(y.providerId).then(function(i) {
                n.currentProvider = i.data;
                t.resolve(!0)
            }), t.promise
        },
        or = function(n) {
            var t, i, u, r;
            if (n && n.diagnoseRecordList) {
                for (t = "", i = 0; i < n.diagnoseRecordList.length; ++i) u = "", n.diagnoseRecordList[i].diagnose && (t = t + n.diagnoseRecordList[i].diagnose, r = n.diagnoseRecordList[i].diagnose.slice(-1), r != "。" && (t = t + "。"));
                return t != "。" ? t : ""
            }
            return ""
        },
        sr = function(n) {
            var i, t, r;
            if (n && n.treatmentAdviceList) {
                for (i = "", t = 0; t < n.treatmentAdviceList.length; ++t) n.treatmentAdviceList[t].content = n.treatmentAdviceList[t].content ? n.treatmentAdviceList[t].content : "", n.treatmentAdviceList[t].content && (i = i + n.treatmentAdviceList[t].content, r = n.treatmentAdviceList[t].content.slice(-1), r != "。" && (i = i + "。"));
                return i != "。" ? i : ""
            }
            return ""
        },
        hr = function(n) {
            var t, i, r;
            if (n && n.treatmentPlanList) {
                for (t = "", i = 0; i < n.treatmentPlanList.length; ++i) n.treatmentPlanList[i].planContent && (t = t + n.treatmentPlanList[i].planContent, r = n.treatmentPlanList[i].planContent.slice(-1), r != "。" && (t = t + "。"));
                return t != "。" ? t : ""
            }
            return ""
        },
        cr = function() {
            st.subscribe(n, st.events.EMRLeave, function(n, t) {
                lr(t)
            })
        },
        lr = function(t) {
            var f, u, r;
            if (Ares.ensureNotDuplicated("OnEmrSaved")) {
                if (n.getDoctor() === -1) {
                    s.warn("信息", "请选择一个医生！");
                    return
                }
                if (!n.currentMedicalRecord.appointId) {
                    s.warn("信息", "没有关联的就诊时间，请先创建一次预约，填写就诊病历！");
                    return
                }
                if (f = si(), f) {
                    s.warn("信息", f);
                    return
                }(n.historyAppts = angular.copy(n.tempHistoryAppts || n.historyAppts), u = _.find(n.historyAppts, function(t) {
                    return t.id === n.currentMedicalRecord.appointId
                }), !u && n.historyAppts.length > 0 && (n.currentMedicalRecord.appointId = n.historyAppts[0].id, u = n.historyAppts[0]), n.isUpdating = !0, n.currentMedicalRecord.appointDateTime = u ? u.startTime : null, nr()) && (n.setNurse(), n.setDoctor(), n.setSuperiorDoctor(), r = angular.copy(n.currentMedicalRecord), r.cureRecordList = hi(), r.oralCheckRecordList = ci(), r.radiologyCheckRecordList = li(), r.diagnoseRecordList = ai(), r.treatmentPlanList = ki(), r.associatedImageList = bi(), r.treatmentAdviceList = gi(), r.fieldList = di(), r.advice = vi(), r.chiefComplaint = wi(), r.history = yi(), r.pastHistory = pi(), r.id === 0 ? w.createMedicalRecord(r).success(function(r) {
                    var u, f;
                    n.currentMedicalRecord.id = r.id;
                    n.currentMedicalRecord.appointId === -2 && (u = _.find(n.historyAppts, function(t) {
                        return t.id === n.currentMedicalRecord.appointId
                    }), u.id = r.appointId, n.currentMedicalRecord.appointId = r.appointId);
                    f = n.currentMedicalRecord.appointId;
                    t && (t.patientId ? (e.current._hasConfirmed = !0, b.goToPatient(t.patientId, t.menuId, t.toParams)) : (e.current._hasConfirmed = !0, b.goToState(t.url, t.toParams)));
                    i(function() {
                        it.success("病历保存成功")
                    })
                }).error(function(n) {
                    n.name === "MedicalRecordRequireApproveException" ? oi(r, n.message, n.data) : n.name !== "AresBusinessException" && it.error("病历记录保存失败")
                }) : w.updateMedicalRecord(r).success(function() {
                    t && (t.patientId ? (e.current._hasConfirmed = !0, b.goToPatient(t.patientId, t.menuId, t.toParams)) : (e.current._hasConfirmed = !0, b.goToState(t.url, t.toParams)));
                    i(function() {
                        it.success("病历保存成功")
                    })
                }).error(function(n) {
                    n.name !== "AresBusinessException" && it.error("病历记录保存失败")
                }))
            }
        },
        ar = function(n) {
            var t = r.defer();
            return k.medicalRecordLayoutTemplateDic.load().then(function(i) {
                var r = i,
                    u = _.find(r, function(t) {
                        return t.templateCode == n
                    });
                t.resolve(u)
            }), t.promise
        },
        vr = function() {
            var t = r.defer();
            return k.medicalRecordLayoutTemplateDic.load().then(function(i) {
                n.layoutTemplates = i;
                t.resolve()
            }), t.promise
        },
        yr = function() {
            br();
            cr();
            r.all([vr(), lu(), k.emrTemplateItemTreeDic.load()]).then(function() {
                tu().then(function() {
                    r.all([pr(), wr(), iu(), dr(), gr(), ]).then(function() {
                        uu();
                        ru().then(function() {
                            eu()
                        });
                        n.initPrint();
                        hf();
                        cf()
                    })
                })
            })
        },
        pr = function() {
            var t = r.defer();
            return k.providerPictureDic.load().then(function(i) {
                var i = _.filter(i, function(n) {
                    return n.proivderPictureType == v.ProivderPictureType.Signature
                });
                n.providerPictures = i;
                t.resolve(i)
            }), t.promise
        },
        wr = function() {
            var t = r.defer();
            return k.doctorDic.loadActive().then(function(i) {
                n.providers = i;
                t.resolve(!0)
            }), t.promise
        },
        br = function() {
            var t = k.officeDic.getItemSync(y.officeId);
            n.office = t
        },
        kr = function(t) {
            var i = _.find(n.providers, function(n) {
                return n.id === t.doctorId
            });
            t.department = i ? i.department : ""
        },
        dr = function() {
            var t = r.defer();
            return w.getLitePatient(n.patientId).success(function(i) {
                i.age = ut.getPatientAge(i);
                n.patient = i;
                n.patient.mcAccount != null && n.patient.mcAccount != "" && (n.enableWeixinSendEmr = !0);
                t.resolve(i)
            }), t.promise
        },
        gr = function() {
            var t = r.defer();
            return w.getBodyCheck(n.patientId).success(function(i) {
                n.bodyCheck = i;
                t.resolve(i)
            }), t.promise
        },
        nu = function() {
            var t = {
                chiefComplaint: "",
                history: "",
                pastHistory: "",
                advice: "",
                doctorName: "",
                doctorId: 0,
                nurseName: "",
                nurseId: 0,
                comment: "",
                archive: "",
                recordDateTime: moment(new Date).format("YYYY-MM-DD HH:mm:ss"),
                diagnoseRecordList: [],
                cureRecordList: [],
                oralCheckRecordList: [],
                radiologyCheckRecordList: [],
                treatmentPlanList: [],
                treatmentAdviceList: [],
                fieldList: [],
                associatedImageList: []
            };
            t.treatmentPlanList.push(pt("治疗计划"));
            t.cureRecordList.push(pt("治疗"));
            t.oralCheckRecordList.push(pt("口腔检查"));
            t.radiologyCheckRecordList.push(pt("辅助检查"));
            t.diagnoseRecordList.push(pt("诊断"));
            t.treatmentAdviceList.push(pt("治疗建议"));
            _.extend(n.currentMedicalRecord, t);
            _.each(n.currentMedicalRecord.customizeFields, function(n) {
                n.fieldValue = null
            })
        },
        tu = function() {
            var t = r.defer();
            return g.getOfficeEmrSetting().success(function(i) {
                n.officeEmrSetings = i;
                n.officeEmrSetingsCache = angular.copy(i);
                tf().then(function() {
                    wu();
                    bu(n.officeEmrSetings.firstEmrTemplateFields);
                    ku(n.officeEmrSetings.secondEmrTemplateFields);
                    rt.getConfigValue(rt.configKeys.AllowToothFDI).then(function(i) {
                        n.allowToothFDI = i ? i : !1;
                        rt.getConfigValue(rt.configKeys.IsEnableEMRLittleToothPrint).then(function(i) {
                            n.allowLittleToothPrint = i ? i : !1;
                            t.resolve(!0)
                        })
                    });
                    af()
                })
            }), t.promise
        },
        iu = function() {
            var i = r.defer(),
                u;
            return n.isUpdating = !0, n.isFirstTemplate = !1, n.isEdit ? (u = e.params.medicalRecordId || n.currentMedicalRecord.id, w.getMedicalRecord(u).success(function(r) {
                n.currentMedicalRecord = r;
                ni(r);
                gt();
                t.$broadcast("medicalRecordSaved", n.currentMedicalRecord);
                n.isUpdating = !1;
                i.resolve(!0)
            })) : (n.currentMedicalRecord = {
                id: 0,
                patientId: n.patientId,
                appointId: 0,
                chiefComplaint: "",
                history: "",
                pastHistory: "",
                firstVisit: n.officeEmrSetings.emrConfig.firstEmr,
                advice: "",
                doctorName: "",
                doctorId: 0,
                nurseName: "",
                nurseId: 0,
                comment: "",
                archive: "",
                recordDateTime: moment(new Date).format("YYYY-MM-DD HH:mm:ss"),
                diagnoseRecordList: [],
                cureRecordList: [],
                oralCheckRecordList: [],
                radiologyCheckRecordList: [],
                treatmentPlanList: [],
                treatmentAdviceList: [],
                fieldList: [],
                associatedImageList: []
            }, ni(n.currentMedicalRecord), n.isUpdating = !1, n.isFirstTemplate = !0, gt(), i.resolve(!0)), i.promise
        },
        gt = function() {
            n.currentMedicalRecord.layoutTemplateCode || (n.currentMedicalRecord.layoutTemplateCode = n.currentMedicalRecord.firstVisit === !0 ? h.firstVisitTemplateCode : n.currentMedicalRecord.firstVisit === !1 ? h.secondVisitTemplateCode : n.availableLayoutTemplates[0].templateCode);
            var t = _(n.layoutTemplates).find(function(t) {
                return t.templateCode === n.currentMedicalRecord.layoutTemplateCode
            });
            n.setLayoutTemplate(t)
        },
        ru = function() {
            var t = r.defer();
            return l.getDoctors().success(function(i) {
                n.doctors = i;
                t.resolve(!0)
            }), t.promise
        },
        uu = function() {
            var t = [];
            k.nurseDic.loadActive().then(function(i) {
                angular.forEach(i, function(n) {
                    t.push(n)
                });
                k.assistantDic.loadActive().then(function(i) {
                    angular.forEach(i, function(n) {
                        t.push(n)
                    });
                    n.nurses = t
                })
            })
        },
        ni = function(t) {
            var u = r.defer(),
                i;
            if (du(t), t.isShowOralCheckRecordList)
                if (t.oralCheckRecordList && t.oralCheckRecordList.length > 0)
                    for (i = 0; i < t.oralCheckRecordList.length; ++i) t.oralCheckRecordList[i].fdiToothCodesArray = t.oralCheckRecordList[i].fdiToothCodes != null && t.oralCheckRecordList[i].fdiToothCodes != "" ? t.oralCheckRecordList[i].fdiToothCodes.split(",") : t.oralCheckRecordList[i].fdiToothCodesArray || [], t.oralCheckRecordList[i].description && (t.oralCheckRecordList[i].descriptionStr = t.oralCheckRecordList[i].description.replace(/\n/g, "<br/>"));
                else t.oralCheckRecordList.push(pt("口腔检查"));
            if (t.isShowRadiologyCheckRecordList)
                if (t.radiologyCheckRecordList && t.radiologyCheckRecordList.length > 0)
                    for (i = 0; i < t.radiologyCheckRecordList.length; ++i) t.radiologyCheckRecordList[i].fdiToothCodesArray = t.radiologyCheckRecordList[i].fdiToothCodes != null && t.radiologyCheckRecordList[i].fdiToothCodes != "" ? t.radiologyCheckRecordList[i].fdiToothCodes.split(",") : t.radiologyCheckRecordList[i].fdiToothCodesArray || [], t.radiologyCheckRecordList[i].description && (t.radiologyCheckRecordList[i].descriptionStr = t.radiologyCheckRecordList[i].description.replace(/\n/g, "<br/>"));
                else t.radiologyCheckRecordList.push(pt("辅助检查"));
            if (t.isShowCureRecordList)
                if (t.cureRecordList && t.cureRecordList.length > 0)
                    for (i = 0; i < t.cureRecordList.length; ++i) t.cureRecordList[i].fdiToothCodesArray = t.cureRecordList[i].fdiToothCodes != null && t.cureRecordList[i].fdiToothCodes != "" ? t.cureRecordList[i].fdiToothCodes.split(",") : t.cureRecordList[i].fdiToothCodesArray || [], t.cureRecordList[i].cure && (t.cureRecordList[i].cureStr = t.cureRecordList[i].cure.replace(/\n/g, "<br/>"));
                else t.cureRecordList.push(pt("治疗"));
            if (t.isShowDiagnoseRecordList)
                if (t.diagnoseRecordList && t.diagnoseRecordList.length > 0)
                    for (i = 0; i < t.diagnoseRecordList.length; ++i) t.diagnoseRecordList[i].fdiToothCodesArray = t.diagnoseRecordList[i].fdiToothCodes != null && t.diagnoseRecordList[i].fdiToothCodes != "" ? t.diagnoseRecordList[i].fdiToothCodes.split(",") : t.diagnoseRecordList[i].fdiToothCodesArray || [], t.diagnoseRecordList[i].diagnose && (t.diagnoseRecordList[i].diagnoseStr = t.diagnoseRecordList[i].diagnose.replace(/\n/g, "<br/>"));
                else t.diagnoseRecordList.push(pt("诊断"));
            if (t.isShowTreatmentPlanList)
                if (t.treatmentPlanList && t.treatmentPlanList.length > 0)
                    for (i = 0; i < t.treatmentPlanList.length; ++i) t.treatmentPlanList[i].fdiToothCodesArray = t.treatmentPlanList[i].fdiToothCodes != null && t.treatmentPlanList[i].fdiToothCodes != "" ? t.treatmentPlanList[i].fdiToothCodes.split(",") : t.treatmentPlanList[i].fdiToothCodesArray || [], t.treatmentPlanList[i].planContent && (t.treatmentPlanList[i].planContentStr = t.treatmentPlanList[i].planContent.replace(/\n/g, "<br/>"));
                else t.treatmentPlanList.push(pt("治疗计划"));
            if (t.isShowTreatmentAdviceList)
                if (t.treatmentAdviceList && t.treatmentAdviceList.length > 0)
                    for (i = 0; i < t.treatmentAdviceList.length; ++i) t.treatmentAdviceList[i].fdiToothCodesArray = t.treatmentAdviceList[i].fdiToothCodes != null && t.treatmentAdviceList[i].fdiToothCodes != "" ? t.treatmentAdviceList[i].fdiToothCodes.split(",") : t.treatmentAdviceList[i].fdiToothCodesArray || [], t.treatmentAdviceList[i].content && (t.treatmentAdviceList[i].contentStr = t.treatmentAdviceList[i].content.replace(/\n/g, "<br/>"));
                else t.treatmentAdviceList.push(pt("治疗建议"));
            return at.formatMedicalRecordFields(t), kr(t), n.isChanged = !1, u.resolve(!0), u.promise
        },
        fu = function() {
            if (n.patient && n.currentMedicalRecord.id > 0) {
                var i = {
                    id: n.currentMedicalRecord.id,
                    patientName: n.patient.name,
                    transactionNames: "",
                    isNewSCRM: t.isNewWxEnabled
                };
                c.getAppointment(n.currentMedicalRecord.appointId).success(function(n) {
                    tt.formatAppt(n);
                    i.transactionNames = n.transactionNames || i.transactionNames;
                    w.sendWeixinMedicalRecord(i).success(function() {
                        s.info("信息", "发送病历成功")
                    })
                })
            }
        },
        ui = function(t) {
            var i = o.open({
                animation: !0,
                backdrop: "static",
                template: "<appt-list-dialog><\/appt-list-dialog>",
                controller: "apptListDialogCtrl",
                size: "md",
                resolve: {
                    host: function() {
                        return {
                            apptList: t,
                            patientId: n.patientId,
                            type: "emr"
                        }
                    }
                }
            });
            i.result.then(function(t) {
                t && (n.selectDropDown(t.id, "appoint"), y.isDoctor ? n.selectDropDown(y.providerId, "doctor") : n.selectDropDown(t.doctorId, "doctor"), n.currentMedicalRecord.appointId = t.id, n.appt.startTime = t.startTime);
                gt()
            })
        },
        eu = function() {
            var t = {
                officeId: y.officeId,
                patientId: n.patientId,
                endTime: moment(Ares.today()).add(1, "d").format(h.dateFormat),
                isCancelled: !1,
                isPending: !1,
                isFailed: !1
            };
            c.searchAppointments(t).success(function(t) {
                var e, r, o, s, f, c, v;
                if (t.length > 0) {
                    for (n.isEnabledTimePicker(!1), e = angular.copy(t), r = 0; r < t.length; ++r) t[r].startTimeStr = moment(t[r].startTime).format("YYYY年MM月DD日 HH:mm");
                    if (n.historyAppts = t, n.currentMedicalRecord.id == 0) {
                        n.currentMedicalRecord.appointId = t[0].id;
                        o = _(n.availableLayoutTemplates).any(function(n) {
                            return n.templateCode === h.firstVisitTemplateCode
                        });
                        s = _(n.availableLayoutTemplates).any(function(n) {
                            return n.templateCode === h.secondVisitTemplateCode
                        });
                        n.currentMedicalRecord.layoutTemplateCode = n.availableLayoutTemplates[0].templateCode;
                        o && t[0].isFirstVisit && (n.currentMedicalRecord.layoutTemplateCode = h.firstVisitTemplateCode);
                        s && !t[0].isFirstVisit && (n.currentMedicalRecord.layoutTemplateCode = h.secondVisitTemplateCode);
                        n.currentMedicalRecord.firstVisit = t[0].isFirstVisit;
                        n.currentMedicalRecord.doctorId = t[0].doctorId;
                        n.selectDropDown(t[0].doctorId, "doctor");
                        var l = moment(Ares.today()).format(h.dateFormat),
                            a = moment(Ares.today()).add(1, "d").format(h.dateFormat),
                            u = _.filter(e, function(n) {
                                return n.startTime >= l && n.startTime < a
                            });
                        u && u.length > 1 && ui(u)
                    }
                } else f = ti(), n.isEnabledTimePicker(!0), c = moment(f.startTime).format("YYYY年MM月DD日 HH:mm"), v = {
                    startTimeStr: c,
                    id: -2,
                    startTime: f.startTime
                }, n.historyAppts = [], i(function() {
                    su()
                });
                gt()
            })
        },
        ou = function() {
            var i = $("#appoint").data("kendoDropDownList"),
                t = {
                    officeId: y.officeId,
                    patientId: n.patientId,
                    startTime: moment(n.appt.startTime).format(h.dateFormat),
                    endTime: moment(n.appt.startTime).add(1, "d").format(h.dateFormat),
                    isCancelled: !1,
                    isFailed: !1,
                    isPending: !1
                };
            c.searchAppointmentsByTenant(t).success(function(t) {
                var u, i, e;
                if (n.isEnabledTimePicker(!1), t.length == 1) n.selectDropDown(t[0].id, "appoint"), n.currentMedicalRecord.appointId = t[0].id, y.isDoctor ? n.selectDropDown(y.providerId, "doctor") : n.selectDropDown(t[0].doctorId, "doctor");
                else if (t.length > 1) u = angular.copy(t), ui(u);
                else {
                    i = ti();
                    n.isEnabledTimePicker(!0);
                    var o = moment(i.startTime).format("YYYY年MM月DD日 HH:mm"),
                        f = {
                            startTimeStr: o,
                            id: -2,
                            startTime: i.startTime
                        },
                        s = _.filter(n.historyAppts, function(n) {
                            return n.id != -2
                        }),
                        r = angular.copy(s);
                    n.tempHistoryAppts = r;
                    n.tempAppointTime = i.startTime;
                    r.push(f);
                    n.currentMedicalRecord.appointId = -2;
                    e = _.find(n.historyAppts, function(n) {
                        return !n.isFailed && !n.isCanceled
                    });
                    e != null && (i.isFirstVisit = !1);
                    n.refreshApptDropDown(f, r)
                }
            })
        },
        su = function() {
            var t = ti(),
                u = moment(t.startTime).format("YYYY年MM月DD日 HH:mm"),
                r = {
                    startTimeStr: u,
                    id: -2,
                    startTime: t.startTime
                },
                i = angular.copy(n.historyAppts),
                f;
            n.tempHistoryAppts = i;
            n.tempAppointTime = t.startTime;
            i.push(r);
            n.currentMedicalRecord.appointId = -2;
            f = _.find(n.historyAppts, function(n) {
                return !n.isFailed && !n.isCanceled
            });
            n.refreshApptDropDown(r, i)
        },
        ti = function() {
            var t = hu();
            return {
                startTime: t.startDate,
                endTime: t.endDate,
                patientId: n.patientId,
                doctorId: n.currentMedicalRecord.doctorId,
                isFirstVisit: n.currentMedicalRecord.firstVisit
            }
        },
        hu = function() {
            var r = new Date,
                t, i, u, f;
            return n.appt.startTime = n.appt.startTime || r, n.appt.startTime.setHours(r.getHours()), n.appt.startTime.setMinutes(r.getMinutes()), t = moment(n.appt.startTime), i = moment().format("mm") * 1, i < 15 ? t.minutes(15) : i > 15 && i < 30 ? t.minutes(30) : i > 30 && i < 45 ? t.minutes(45) : i > 45 && (t.minutes(0), t.add(1, "hour")), u = moment(t).format("YYYY-MM-DD HH:mm"), f = moment(u).add(30, "m").format("YYYY-MM-DD HH:mm"), {
                startDate: u,
                endDate: f
            }
        },
        cu = function(t) {
            Ares.sensors.track("PatientNewEmrEdit", {
                InputName: t
            });
            n.isInput = !0
        },
        pt = function(n) {
            return n === "口腔检查" ? {
                id: 0,
                description: "",
                fdiToothCodesArray: [],
                fdiToothCodes: ""
            } : n === "辅助检查" ? {
                id: 0,
                description: "",
                fdiToothCodesArray: []
            } : n === "诊断" ? {
                id: 0,
                diagnose: "",
                fdiToothCodesArray: []
            } : n === "治疗计划" ? {
                id: 0,
                planContent: "",
                fdiToothCodesArray: []
            } : n === "治疗" ? {
                id: 0,
                cure: "",
                fdiToothCodesArray: []
            } : n === "治疗建议" ? {
                id: 0,
                content: "",
                fdiToothCodesArray: []
            } : void 0
        },
        ii = function(t, i) {
            (n.templateTreeControl = new ft.TreeControl(t, i), n.templateTreeControl) && (n.treeData = n.templateTreeControl.getTree(), n.topLevelNode = n.treeData)
        },
        lu = function() {
            var t = r.defer();
            return w.listDiseaseItems(v.DiseaseType.Default).success(function(i) {
                n.diseaseItems = i;
                t.resolve()
            }), t.promise
        },
        au = function() {
            var t = n.emrLayoutTemplate.templateCode,
                i = at.getTemplateTypeByCode(t);
            w.listEMRTemplates(i, t).success(function(t) {
                n.emrTemplates = t;
                ii(n.diseaseItems, t)
            })
        },
        vu = function() {
            var t = n.currentMedicalRecord.layoutTemplateCode,
                i = at.getTemplateTypeByCode(t);
            w.listEMRTemplates(i, t).success(function(t) {
                n.emrTemplates = t;
                ii(n.diseaseItems, n.emrTemplates)
            })
        },
        vf = function() {
            for (var t, u, i, r = 0; r < n.emrTemplateItems.length; ++r)
                for (t = n.emrTemplateItems[r], u = 0; u < n.notTopLevelNode.length; ++u) i = n.notTopLevelNode[u], t.diseaseId == i.id && (i[t.mainType + t.subType] || (i[t.mainType + t.subType] = []), i[t.mainType + t.subType].push(t))
        },
        yf = function(t) {
            var i;
            for (n.currentEmrTemplateItem = angular.copy(t), i = 0; i < n.templateItemGridList.length; ++i) {
                var r = n.templateItemGridList[i],
                    u = $(r.gridId).data("kendoGrid"),
                    f = new kendo.data.DataSource({
                        data: n.currentEmrTemplateItem[r.maintype + r.gridName],
                        schema: {
                            model: {
                                fields: {
                                    itemName: {
                                        type: "string",
                                        editable: !1
                                    }
                                }
                            }
                        }
                    });
                u.setDataSource(f)
            }
        },
        yu = function() {
            var t = o.open({
                animation: !0,
                backdrop: "static",
                template: "<system-setting-item-edit><\/system-setting-item-edit>",
                controller: "SystemSettingItemEditCtrl",
                resolve: {
                    host: function() {
                        return {
                            itemType: "病历归档"
                        }
                    },
                    boxTitle: function() {
                        return ""
                    }
                }
            });
            t.result.then(function() {
                n.currentMedicalRecord.archive = "";
                n.initArchiveDropdown()
            })
        },
        fi = function() {
            return angular.copy(n.currentMedicalRecord)
        },
        pu = function(r) {
            var e, f, u;
            if (Ares.ensureNotDuplicated("OnEmrSaved")) {
                if (n.getDoctor() == -1) {
                    s.warn("信息", "请选择一个医生！");
                    return
                }
                if (!n.currentMedicalRecord.appointId) {
                    s.warn("信息", "没有关联的就诊时间，请先创建一次预约，填写就诊病历！");
                    return
                }
                if (e = si(), e) {
                    s.warn("信息", e);
                    return
                }(n.historyAppts = angular.copy(n.tempHistoryAppts || n.historyAppts), f = _.find(n.historyAppts, function(t) {
                    return t.id == n.currentMedicalRecord.appointId
                }), !f && n.historyAppts.length > 0 && (n.currentMedicalRecord.appointId = n.historyAppts[0].id, f = n.historyAppts[0]), n.isUpdating = !0, n.currentMedicalRecord.appointDateTime = f ? f.startTime : null, nr()) && (n.setNurse(), n.setDoctor(), n.setSuperiorDoctor(), u = angular.copy(n.currentMedicalRecord), u.cureRecordList = hi(), u.oralCheckRecordList = ci(), u.radiologyCheckRecordList = li(), u.diagnoseRecordList = ai(), u.treatmentPlanList = ki(), u.associatedImageList = bi(), u.treatmentAdviceList = gi(), u.fieldList = di(), u.advice = vi(), u.chiefComplaint = wi(), u.history = yi(), u.pastHistory = pi(), u.id === 0 ? w.createMedicalRecord(u).success(function(n) {
                    ei(n, r)
                }).error(function(n) {
                    n.name == "MedicalRecordRequireApproveException" ? oi(u, n.message, n.data) : n.name != "AresBusinessException" && it.error("病历记录保存失败")
                }) : w.updateMedicalRecord(u).success(function(u) {
                    var f, e, o;
                    n.currentMedicalRecord.appointId == -2 && (f = _.find(n.historyAppts, function(n) {
                        return n.id == -2
                    }), e = _.find(n.tempHistoryAppts || [], function(n) {
                        return n.id == -2
                    }), f && (f.id = u), e && (e.id = u), n.currentMedicalRecord.appointId = u);
                    o = n.currentMedicalRecord.appointId;
                    r && c.completeAppointment(o).success(function() {
                        b.allowLeave();
                        b.switchState("patientgeneralMedicalRecords.patientEmr.list", {
                            patientId: n.patientId
                        })
                    });
                    n.originalMedicalRecord = fi();
                    t.$broadcast("medicalRecordSaved", n.currentMedicalRecord);
                    i(function() {
                        n.isChanged = !1;
                        n.isUpdating = !1;
                        it.success("病历保存成功")
                    })
                }).error(function(n) {
                    n.name != "AresBusinessException" && it.error("病历记录保存失败")
                }), r ? Ares.sensors.track("PatientNewEmrEditCtrl", {
                    PatientName: n.patient.name,
                    OperationType: "完成治疗"
                }) : Ares.sensors.track("PatientNewEmrEditCtrl", {
                    PatientName: n.patient.name,
                    OperationType: "保存"
                }))
            }
        },
        ei = function(r, u, f) {
            var e, o, s;
            n.currentMedicalRecord.id = r.id;
            f && (n.currentMedicalRecord.workflowStatus = f);
            n.currentMedicalRecord.appointId == -2 && (e = _.find(n.historyAppts, function(n) {
                return n.id == -2
            }), o = _.find(n.tempHistoryAppts || [], function(n) {
                return n.id == -2
            }), e && (e.id = r.appointId), o && (o.id = r.appointId), n.currentMedicalRecord.appointId = r.appointId);
            s = n.currentMedicalRecord.appointId;
            u && c.completeAppointment(s).success(function() {
                b.allowLeave();
                b.switchState("patientgeneralMedicalRecords.patientEmr.list", {
                    patientId: n.patientId
                })
            });
            n.originalMedicalRecord = fi();
            t.$broadcast("medicalRecordSaved", n.currentMedicalRecord);
            i(function() {
                n.isChanged = !1;
                n.isUpdating = !1;
                n.isEdit = !0;
                it.success("病历保存成功")
            })
        },
        oi = function(n, t, i) {
            var r = JSON.parse(i);
            yt.approvalConfirmDialog("带教老师病例审批确认", t, r).then(function(t) {
                n.actorIds = t;
                et.applyMedicalRecordWorkflow(n).success(function(n) {
                    ei(n, !1, 1)
                }).error(function(n) {
                    n.name != "AresBusinessException" && it.error("病历记录保存失败")
                })
            })
        },
        si = function() {
            var t, i;
            return n.hasOralCheckRecord && n.currentMedicalRecord.isShowOralCheckRecordList && n.currentMedicalRecord.oralCheckRecordList && (t = _.any(n.currentMedicalRecord.oralCheckRecordList, function(n) {
                return n.fdiToothCodesArray && n.fdiToothCodesArray.length > 0 && n.description == ""
            }), t) ? (i = n.isEmrCustomTemplateEnabled ? "检查" : "口腔检查", "【" + i + "】中牙位缺少描述。") : n.hasRadiologyCheckRecord && n.currentMedicalRecord.isShowRadiologyCheckRecordList && n.currentMedicalRecord.radiologyCheckRecordList && (t = _.any(n.currentMedicalRecord.radiologyCheckRecordList, function(n) {
                return n.fdiToothCodesArray && n.fdiToothCodesArray.length > 0 && n.description == ""
            }), t) ? (i = n.isEmrCustomTemplateEnabled ? "X线检查示" : "辅助检查", "【" + i + "】中牙位缺少描述。") : n.hasDiagnoseRecord && n.currentMedicalRecord.isShowDiagnoseRecordList && n.currentMedicalRecord.diagnoseRecordList && (t = _.any(n.currentMedicalRecord.diagnoseRecordList, function(n) {
                return n.fdiToothCodesArray && n.fdiToothCodesArray.length > 0 && n.diagnose == ""
            }), t) ? "【诊断】中牙位缺少描述。" : n.hasTreatmentPlan && n.currentMedicalRecord.isShowTreatmentPlanList && n.currentMedicalRecord.treatmentPlanList && (t = _.any(n.currentMedicalRecord.treatmentPlanList, function(n) {
                return n.fdiToothCodesArray && n.fdiToothCodesArray.length > 0 && n.planContent == ""
            }), t) ? "【治疗方案】中牙位缺少描述。" : n.hasTreatmentAdvice && n.currentMedicalRecord.isShowTreatmentAdviceList && n.currentMedicalRecord.treatmentAdviceList && (t = _.any(n.currentMedicalRecord.treatmentAdviceList, function(n) {
                return n.fdiToothCodesArray && n.fdiToothCodesArray.length > 0 && n.content == ""
            }), t) ? "【治疗建议】中牙位缺少描述。" : n.hasCureRecord && n.currentMedicalRecord.isShowCureRecordList && n.currentMedicalRecord.cureRecordList && (t = _.any(n.currentMedicalRecord.cureRecordList, function(n) {
                return n.fdiToothCodesArray && n.fdiToothCodesArray.length > 0 && n.cure == ""
            }), t) ? (i = n.isEmrCustomTemplateEnabled ? "处理" : "处置", "【" + i + "】中牙位缺少描述。") : ""
        },
        hi = function() {
            var t = [];
            return n.hasCureRecord && n.currentMedicalRecord.isShowCureRecordList && angular.forEach(n.currentMedicalRecord.cureRecordList, function(n) {
                var i = kt(n.cure);
                i.length > 0 && (n.fdiToothCodes = n.fdiToothCodesArray && n.fdiToothCodesArray.length > 0 ? n.fdiToothCodesArray.join(",") : "", t.push(n))
            }), t
        },
        ci = function() {
            var t = [];
            return n.hasOralCheckRecord && n.currentMedicalRecord.isShowOralCheckRecordList && angular.forEach(n.currentMedicalRecord.oralCheckRecordList, function(n) {
                var i = kt(n.description),
                    r = kt(n.observationName);
                (i.length > 0 || r.length > 0) && (n.fdiToothCodes = n.fdiToothCodesArray && n.fdiToothCodesArray.length > 0 ? n.fdiToothCodesArray.join(",") : "", t.push(n))
            }), t
        },
        li = function() {
            var t = [];
            return n.hasRadiologyCheckRecord && n.currentMedicalRecord.isShowRadiologyCheckRecordList && angular.forEach(n.currentMedicalRecord.radiologyCheckRecordList, function(n) {
                var i = kt(n.description);
                i.length > 0 && (n.fdiToothCodes = n.fdiToothCodesArray && n.fdiToothCodesArray.length > 0 ? n.fdiToothCodesArray.join(",") : "", t.push(n))
            }), t
        },
        ai = function() {
            var t = [];
            return n.hasDiagnoseRecord && n.currentMedicalRecord.isShowDiagnoseRecordList && angular.forEach(n.currentMedicalRecord.diagnoseRecordList, function(n) {
                var i = kt(n.diagnose);
                i.length > 0 && (n.fdiToothCodes = n.fdiToothCodesArray && n.fdiToothCodesArray.length > 0 ? n.fdiToothCodesArray.join(",") : "", t.push(n))
            }), t
        },
        vi = function() {
            var t = "";
            return n.hasAdvice && n.currentMedicalRecord.isShowAdvice && (t = n.currentMedicalRecord.advice), t
        },
        yi = function() {
            var t = "";
            return n.hasHistory && n.currentMedicalRecord.isShowHistory && (t = n.currentMedicalRecord.history), t
        },
        pi = function() {
            var t = "";
            return n.hasPastHistory && n.currentMedicalRecord.isShowPastHistory && (t = n.currentMedicalRecord.pastHistory), t
        },
        wi = function() {
            var t = "";
            return n.hasChiefComplaint && n.currentMedicalRecord.isShowChiefComplaint && (t = n.currentMedicalRecord.chiefComplaint), t
        },
        bi = function() {
            var t = [];
            return n.hasAssociatedImage && n.currentMedicalRecord.isShowAssociatedImage && (t = n.currentMedicalRecord.associatedImageList.map(function(n) {
                return {
                    id: n.id,
                    imageId: n.imageId,
                    mgmtType: n.mgmtType,
                    note: n.note,
                    medicalRecordId: n.medicalRecordId ? n.medicalRecordId : 0
                }
            })), t
        },
        ki = function() {
            var t = [];
            return n.hasTreatmentPlan && n.currentMedicalRecord.isShowTreatmentPlanList && angular.forEach(n.currentMedicalRecord.treatmentPlanList, function(n) {
                var i = kt(n.planContent);
                i.length > 0 && (n.fdiToothCodes = n.fdiToothCodesArray && n.fdiToothCodesArray.length > 0 ? n.fdiToothCodesArray.join(",") : "", t.push(n))
            }), t
        },
        di = function() {
            var t = [];
            return n.currentMedicalLayoutFields && n.currentMedicalRecord.customizeFields && _.each(n.currentMedicalRecord.customizeFields, function(i, r) {
                var u = n.currentMedicalLayoutFields[r];
                i.fieldValue && u && t.push(i)
            }), t
        },
        gi = function() {
            var t = [];
            return n.hasTreatmentAdvice && n.currentMedicalRecord.isShowTreatmentAdviceList && angular.forEach(n.currentMedicalRecord.treatmentAdviceList, function(n) {
                var i = kt(n.content);
                i.length > 0 && (n.fdiToothCodes = n.fdiToothCodesArray && n.fdiToothCodesArray.length > 0 ? n.fdiToothCodesArray.join(",") : "", t.push(n))
            }), t
        },
        kt = function(n) {
            return !n || !angular.isString(n) ? "" : n.replace(/(^\s*)|(\s*$)/g, "")
        },
        wu = function() {
            if (n.officeEmrSetings) {
                var i = n.officeEmrSetings.emrCategory ? n.officeEmrSetings.emrCategory.split("|") : [],
                    t = {};
                n.availableLayoutTemplates = [];
                _.each(n.layoutTemplates, function(r) {
                    t[r.templateCode] = _(i).include(r.templateCode);
                    t[r.templateCode] && n.availableLayoutTemplates.push(r)
                });
                n.officeEmrSetings.emrConfig = t
            }
        },
        bu = function(t) {
            if (t) {
                var t = t.split("|"),
                    i = _.indexOf(t, "chiefComplaint") > -1,
                    r = _.indexOf(t, "history") > -1,
                    u = _.indexOf(t, "pastHistory") > -1,
                    f = _.indexOf(t, "oralCheck") > -1,
                    e = _.indexOf(t, "radiologyCheck") > -1,
                    o = _.indexOf(t, "treatmentPlan") > -1,
                    s = _.indexOf(t, "diagnose") > -1,
                    h = _.indexOf(t, "cure") > -1,
                    c = _.indexOf(t, "advice") > -1,
                    l = _.indexOf(t, "treatmentAdvice") > -1,
                    a = _.indexOf(t, "associatedImage") > -1,
                    v = {
                        chiefComplaint: i,
                        history: r,
                        pastHistory: u,
                        oralCheck: f,
                        radiologyCheck: e,
                        diagnose: s,
                        treatmentAdvice: l,
                        treatmentPlan: o,
                        cure: h,
                        advice: c,
                        associatedImage: a
                    };
                n.officeEmrSetings.firstEmrTemplateFields = v
            }
        },
        ku = function(t) {
            if (t) {
                var t = t.split("|"),
                    i = _.indexOf(t, "chiefComplaint") > -1,
                    r = _.indexOf(t, "oralCheck") > -1,
                    u = _.indexOf(t, "radiologyCheck") > -1,
                    f = _.indexOf(t, "treatmentPlan") > -1,
                    e = _.indexOf(t, "diagnose") > -1,
                    o = _.indexOf(t, "cure") > -1,
                    s = _.indexOf(t, "advice") > -1,
                    h = _.indexOf(t, "history") > -1,
                    c = _.indexOf(t, "pastHistory") > -1,
                    l = _.indexOf(t, "treatmentAdvice") > -1,
                    a = _.indexOf(t, "associatedImage") > -1,
                    v = {
                        chiefComplaint: i,
                        history: h,
                        pastHistory: c,
                        oralCheck: r,
                        radiologyCheck: u,
                        diagnose: e,
                        treatmentAdvice: l,
                        treatmentPlan: f,
                        cure: o,
                        advice: s,
                        associatedImage: a
                    };
                n.officeEmrSetings.secondEmrTemplateFields = v
            }
        },
        du = function(t) {
            if (n.currentMedicalRecord) {
                var i = _.find(n.currentMedicalRecord.oralCheckRecordList, function(n) {
                        return n.description != ""
                    }),
                    r = _.find(n.currentMedicalRecord.radiologyCheckRecordList, function(n) {
                        return n.description != ""
                    }),
                    u = _.find(n.currentMedicalRecord.treatmentPlanList, function(n) {
                        return n.planContent != ""
                    }),
                    f = _.find(n.currentMedicalRecord.diagnoseRecordList, function(n) {
                        return n.diagnose != ""
                    }),
                    e = _.find(n.currentMedicalRecord.cureRecordList, function(n) {
                        return n.cure != ""
                    }),
                    o = _.find(n.currentMedicalRecord.associatedImageList, function(n) {
                        return n.id !== 0
                    });
                t.isShowOralCheckRecordList = wt("oralCheck", "oralCheckRecordList", i);
                t.isShowRadiologyCheckRecordList = wt("radiologyCheck", "radiologyCheckRecordList", r);
                t.isShowTreatmentPlanList = wt("treatmentPlan", "treatmentPlanList", u);
                t.isShowTreatmentAdviceList = n.isDiseaseCertificateEnabled;
                t.isShowDiagnoseRecordList = wt("diagnose", "diagnoseRecordList", f);
                t.isShowCureRecordList = wt("cure", "cureRecordList", e);
                t.isShowHistory = wt("history", null, null);
                t.isShowPastHistory = wt("pastHistory", null, null);
                t.isShowChiefComplaint = wt("chiefComplaint", null, null);
                t.isShowAdvice = wt("advice", null, null);
                t.isShowAssociatedImage = wt("associatedImage", "associatedImageList", o)
            }
        },
        gu = ["chiefComplaint", "history", "pastHistory", "oralCheck", "radiologyCheck", "treatmentPlan", "diagnose", "cure", "advice", "associatedImage"],
        nf = function() {
            var t = angular.copy(n.officeEmrSetingsCache),
                u = t.firstEmrTemplateFields.split("|"),
                f = t.secondEmrTemplateFields.split("|"),
                i = n.emrLayoutTemplate.templateCode === h.firstVisitTemplateCode,
                e = n.emrLayoutTemplate.templateCode === h.secondVisitTemplateCode,
                o = i ? u : f,
                r = [];
            n.emrLayoutTemplate && n.emrLayoutTemplate.rootFields && vt.getEmrCategories().forEach(function(t) {
                var f = t,
                    u = n.emrLayoutTemplate.rootFields.filter(n => n.category === t);
                u.length > 0 && (u = _(u).sortBy(function(n) {
                    return n.seqNum
                }), r.push({
                    parent: f,
                    child: _(u).pluck("fieldName").filter(function(t) {
                        return t === "treatmentAdvice" ? n.isDiseaseCertificateEnabled : !i && !e ? !0 : !_(gu).contains(t) || _(o).contains(t)
                    })
                }))
            });
            n.emrTemplateFieldsArray = r;
            n.thisIndex = 0
        },
        tf = function() {
            var t = r.defer();
            return nt.getOfficeOption(nt.optionKeys.IsEmrCustomTemplateEnabled).then(function(i) {
                i == "1" && (n.isEmrCustomTemplateEnabled = !0);
                rf().then(function() {
                    t.resolve(!0)
                })
            }), t.promise
        },
        rf = function() {
            var t = r.defer();
            return nt.getOfficeOption(nt.optionKeys.IsDiseaseCertificateEnabled).then(function(i) {
                i == "1" && (n.isDiseaseCertificateEnabled = !0);
                t.resolve(!0)
            }), t.promise
        },
        wt = function(t, i, r) {
            var u = "",
                f;
            return n.currentMedicalRecord.firstVisit === null || n.currentMedicalRecord.firstVisit === undefined ? !0 : (u = n.currentMedicalRecord.firstVisit === !0 ? "firstEmrTemplateFields" : "secondEmrTemplateFields", i != null ? n.isEdit ? n.officeEmrSetings[u][t] || n.currentMedicalRecord[i] && n.currentMedicalRecord[i].length > 0 && r != null : n.officeEmrSetings[u][t] : n.isEdit ? n.officeEmrSetings[u][t] || n.currentMedicalRecord[t] : n.officeEmrSetings[u][t])
        },
        uf = function(t, i) {
            n.isAllowSynchronization && (at.diagnoseImport(t, i, n.currentMedicalRecord.diagnoseRecordList), at.radiologyCheckImport(t, i, n.currentMedicalRecord.radiologyCheckRecordList), at.treatmentAdviceImport(t, i, n.currentMedicalRecord.treatmentAdviceList), at.treatmentPlanImport(t, i, n.currentMedicalRecord.treatmentPlanList), at.cureRecordImport(t, i, n.currentMedicalRecord.cureRecordList))
        },
        ff = function() {
            n.isAllowSynchronization && (n.currentMedicalRecord.diagnoseRecordList && n.currentMedicalRecord.diagnoseRecordList.length > 0 && (n.currentMedicalRecord.diagnoseRecordList = _.filter(n.currentMedicalRecord.diagnoseRecordList, function(n) {
                return !(n.diagnose == "" && n.fdiToothCodesArray.length == 0)
            })), n.currentMedicalRecord.radiologyCheckRecordList && n.currentMedicalRecord.radiologyCheckRecordList.length > 0 && (n.currentMedicalRecord.radiologyCheckRecordList = _.filter(n.currentMedicalRecord.radiologyCheckRecordList, function(n) {
                return !(n.description == "" && n.fdiToothCodesArray.length == 0)
            })), n.currentMedicalRecord.treatmentAdviceList && n.currentMedicalRecord.treatmentAdviceList.length > 0 && (n.currentMedicalRecord.treatmentAdviceList = _.filter(n.currentMedicalRecord.treatmentAdviceList, function(n) {
                return !(n.content == "" && n.fdiToothCodesArray.length == 0)
            })), n.currentMedicalRecord.treatmentPlanList && n.currentMedicalRecord.treatmentPlanList.length > 0 && (n.currentMedicalRecord.treatmentPlanList = _.filter(n.currentMedicalRecord.treatmentPlanList, function(n) {
                return !(n.planContent == "" && n.fdiToothCodesArray.length == 0)
            })), n.currentMedicalRecord.cureRecordList && n.currentMedicalRecord.cureRecordList.length > 0 && (n.currentMedicalRecord.cureRecordList = _.filter(n.currentMedicalRecord.cureRecordList, function(n) {
                return !(n.cure == "" && n.fdiToothCodesArray.length == 0)
            })))
        },
        pf = function(t, i, r) {
            var u = angular.copy(n.currentMedicalRecord[t]);
            u[i] && (u[i].fdiToothCodesArray = r, n.currentMedicalRecord[t] = angular.copy(u))
        },
        bt = [],
        dt = ["oralCheckRecordList", "radiologyCheckRecordList", "diagnoseRecordList", "treatmentPlanList", "cureRecordList", "treatmentAdviceList"],
        ef = function(t) {
            var l, a, i, h, v, r, e, u, c;
            if (t) {
                var f = parseInt(t.index),
                    o = t.listName,
                    y = t.selectedToothCodes,
                    s = n.currentMedicalRecord.oralCheckRecordList;
                for (r = 0; r < s.length; r++) l = s[r], l.isAllowSynchronization && (a = bt.find(n => n.optionIndex == r), a || bt.push({
                    optionIndex: f,
                    syncId: Ares.uuidFast(),
                    added: !1
                }));
                if (o == "oralCheckRecordList" || f === 0 ? i = bt.find(n => n.optionIndex === f) : (h = n.currentMedicalRecord[o][f], h.syncId && (i = bt.find(n => n.syncId == h.syncId))), i && (v = s[i.optionIndex], v.isAllowSynchronization)) {
                    for (r = 0; r < dt.length; r++)
                        if (e = dt[r], e != o) {
                            if (u = n.currentMedicalRecord[e], !u || u.length == 0) continue;
                            !i.added && f > 0 && u.push({
                                id: 0,
                                description: "",
                                observationName: "",
                                fdiToothCodesArray: [],
                                fdiToothCodes: "",
                                syncId: i.syncId
                            });
                            c = e == "oralCheckRecordList" ? u[i.optionIndex] : i.optionIndex > 0 ? u.find(n => n.syncId == i.syncId) : u[0];
                            c && (c.fdiToothCodesArray = y)
                        }
                    i.added = !0
                }
            }
        },
        of = function(t) {
            var v, s, f, h, c, l, i, a, e, o, r, y, u;
            if (t)
                if (v = parseInt(t.index), s = t.listName, s == "oralCheckRecordList") {
                    if (u = bt.findIndex(n => n.optionIndex === v), u > -1 && (f = bt.splice(u, 1)), f && f.length > 0)
                        for (i = 0; i < dt.length; i++)(h = dt[i], h != s) && (r = n.currentMedicalRecord[h], c = r.findIndex(n => n.syncId == f[0].syncId), c > -1 && r.splice(c, 1))
                } else
                    for (l = n.currentMedicalRecord.oralCheckRecordList, i = 0; i < l.length; i++)
                        if (a = bt.find(n => n.optionIndex == i), a) {
                            for (e = !0, o = 1; o < dt.length; o++)
                                if (r = n.currentMedicalRecord[dt[o]], r && r.length > 0 && (y = r.findIndex(n => n.syncId == a.syncId), y > -1)) {
                                    e = !1;
                                    break
                                }
                            e && (l[i].isAllowSynchronization = !e, u = bt.findIndex(n => n.optionIndex == i), u > -1 && bt.splice(u, 1))
                        }
        },
        sf = function(t) {
            n.isInput = !1;
            var r = t.attr("data-list-name"),
                i = t.attr("data-index");
            n.recordTooth = n.isAllowSynchronization && i == "0" ? {
                name: r,
                index: parseInt(i)
            } : null
        },
        hf = function() {
            ut.hasCheckedInToday(n.patientId).then(function(t) {
                n.isCheckedInToday = t.isCheckedIn;
                n.isStrongStrict = t.isStrongStrict
            })
        },
        cf = function() {
            if (n.currentMedicalRecord && n.currentMedicalRecord.id <= 0) {
                n.isAllowSynchronization = !0;
                var t = ri.loadObject();
                t && (n.isAllowSynchronization = t.isAllowSynchronization)
            }
        },
        lf = function() {
            if (n.currentMedicalRecord && n.currentMedicalRecord.id <= 0) {
                var t = {
                    isAllowSynchronization: n.isAllowSynchronization
                };
                ri.saveObject(t)
            }
        },
        af = function() {
            var t = r.defer();
            return nt.getOfficeOption(nt.optionKeys.MedicalRecordQcConfig).then(function(i) {
                n.medicalRecordQcConfig = i;
                t.resolve(!0)
            }), t.promise
        },
        nr = function() {
            if (!n.medicalRecordQcConfig) return !0;
            if (n.currentMedicalRecord.id > 0) {
                if (n.currentMedicalRecord.state !== 1 && n.medicalRecordQcConfig.ModifyTimeLimit > 0 && n.currentMedicalRecord.recordDateTime && moment(n.currentMedicalRecord.recordDateTime).add(n.medicalRecordQcConfig.ModifyTimeLimit, "h") < moment(Ares.today())) return s.warn("信息", "已经超过病历修改限时" + n.medicalRecordQcConfig.ModifyTimeLimit + "小时"), !1
            } else if (n.medicalRecordQcConfig.TaskFinishTimeLimit > 0 && n.currentMedicalRecord.appointDateTime && moment(n.currentMedicalRecord.appointDateTime).add(n.medicalRecordQcConfig.TaskFinishTimeLimit, "h") < moment(Ares.today())) return s.warn("信息", "已经超过病历补写限时" + n.medicalRecordQcConfig.TaskFinishTimeLimit + "小时"), !1;
            return !0
        };
    (function() {
        n.date = new Date;
        n.enableWeixinSendEmr = !1;
        n.appt = {};
        n.today = new Date;
        n.isUpdating = !1;
        n.isFirstTemplate = !0;
        n.isDisableEMRBlankPrint = !1;
        n.Synching = !1;
        n.isEmrCustomTemplateEnabled = !1;
        n.isEdit = e.params.medicalRecordId > 0;
        n.patientId = f.patientId;
        n.onApptTimeChanged = ou;
        n.setEMRControlFocus = cu;
        n.editArchive = yu;
        n.saveEmr = pu;
        n.clear = nu;
        n.sendWeixinMedicalRecord = fu;
        n.showSaveEMRTemplateDlg = tr;
        n.formatMedicalRecord = ni;
        n.toothSynchronization = ef;
        n.deleteToothCode = of ;
        n.onRecordTooth = sf;
        n.removeEmptyRecord = ff;
        n.importTooth = uf;
        n.isInput = !1;
        n.bodyCheck = {};
        n.getEMRTemplates = vu;
        n.isCheckedInToday = !1;
        n.isStrongStrict = !1;
        n.EMRWritingLimitValue = 0;
        n.medicalRecordQcConfig = nt.optionDefaultValues.MedicalRecordQcConfig;
        n.isEnableEMRWritingLimitValue = !1;
        n.onChangeAllowSynchronization = lf;
        n.getCurrentProvider = er;
        n.getMedicalRecordLayoutTemplateByCode = ar;
        n.setEmrTemplateFieldsArray = nf;
        n.setCurrentEMRTemplateSetting = au;
        l.getSystemConfigByName("IsDisableEMRBlankPrint").success(function(t) {
            n.isDisableEMRBlankPrint = t.configValue == "true"
        });
        yr()
    })()
}]);
emrModule.controller("PatientNewEmrExemptionAgreementCtrl", ["$scope", "$modalInstance", function(n, t) {
    "use strict";
    var i = function() {
        t.close()
    };
    (function() {
        n.close = i
    })()
}]);
emrModule.controller("patientNewEmrTemplateSaveDiseaseChoiceCtrl", ["$log", "$scope", "$modalInstance", "loginContext", "host", function(n, t, i, r, u) {
    "use strict";
    var f = u.treeControl,
        e = f.getTree(),
        o = function() {
            i.dismiss("cancel")
        },
        s = function() {
            i.close(t.chosenDisease)
        },
        h = {
            showActionBar: !1,
            showLeafs: !1
        };
    t.selectNode = function(n) {
            t.chosenDisease.id = n.id;
            t.chosenDisease.breadcrumb = f.getBranchBreadcrumbById(n.id).join(" > ");
            t.chosenDisease.departmentName = n.departmentName;
            t.templateDiseaseNotChosen = !1
        },
        function() {
            t.treeControl = f;
            t.treeData = e;
            t.treeOpts = h;
            t.cancel = o;
            t.close = s;
            t.templateDiseaseNotChosen = !0;
            t.chosenDisease = {
                id: null,
                breadcrumb: "",
                departmentName: ""
            }
        }()
}]);
emrModule.controller("PatientNewEmrCtrl", ["$scope", "$timeout", "$state", "$q", "$log", "$stateParams", "$modal", "enums", "aresDialog", "aresNotification", "patientSvc", "practiceSvc", "dataDicSvc", "loginContext", "permissionProvider", "systemConfigUtil", "officeOptionSvc", "patientDocumentSvc", "printTemplateUtil", "patientUtil", "systemConfigSvc", "apptUtil", "providerUtil", "emrUtil", "constants", "officeSvc", function(n, t, i, r, u, f, e, o, s, h, c, l, a, v, y, p, w, b, k, d, g, nt, tt, it, rt) {
    "use strict";
    var ft = "全部标签",
        vt = function() {
            ui();
            r.all([ci(), bt(), kt(), ni(), fi(), oi(), yt(), hi()]).then(function() {
                ht().then(function() {
                    pt();
                    st()
                })
            })
        },
        yt = function() {
            var t = r.defer();
            return a.medicalRecordLayoutTemplateDic.load().then(function(i) {
                n.layoutTemplates = i;
                t.resolve()
            }), t.promise
        },
        ht = function() {
            var t = r.defer();
            return c.getMedicalRecordSummaryByPatientId(n.patientId).success(function(i) {
                et(i);
                n.medicalRecords = i;
                n.copyMedicalRecords = angular.copy(n.medicalRecords);
                var r = [];
                angular.forEach(n.medicalRecords, function(n) {
                    n.isDocument || n.workflowStatus != 1 && r.push({
                        id: n.id,
                        startTime: n.startTime
                    })
                });
                n.MedicalRecordPrintConfig && (n.MedicalRecordPrintConfig.IsByApptTimeAsc || n.MedicalRecordPrintConfig.isByApptTimeAsc) && (r = r.sort((n, t) => Date.parse(n.startTime) - Date.parse(t.startTime)));
                n.redcordIds = [];
                angular.forEach(r, function(t) {
                    n.redcordIds.push("#" + t.id)
                });
                t.resolve()
            }), t.promise
        },
        pt = function() {
            if (n.medicalRecords) {
                var t = _.findIndex(n.medicalRecords, function(t) {
                    return t.medicalRecordId == n.medicalRecordId
                });
                t = t > -1 ? t : 0;
                n.medicalRecords[t] && !n.medicalRecords[t].isDocument && (ot(n.medicalRecords[t]), n.autoScroll())
            }
        },
        wt = function() {
            var i = r.defer(),
                t;
            return n.medicalRecords && (t = [], n.medicalRecords.forEach(function(n) {
                var i = ot(n, null, !0);
                i && t.push(i)
            }), r.all(t).then(function() {
                i.resolve()
            })), i.promise
        },
        bt = function() {
            var t = r.defer();
            return w.getOfficeOptions(["IsEmrCustomTemplateEnabled", "IsMedicalRecordPaginationPrintEnabled", "MedicalRecordPrintConfig"]).then(function(i) {
                i[0] == "1" && (n.isShowCustomBtn = !0, n.isEmrCustomTemplateEnabled = !0);
                n.isMedicalRecordPaginationPrintEnabled = i[1] == "1";
                n.MedicalRecordPrintConfig = i[2];
                t.resolve(!0)
            }), t.promise
        },
        kt = function() {
            var t = r.defer();
            return w.getOfficeOption(w.optionKeys.IsDiseaseCertificateEnabled).then(function(i) {
                i == "1" && (n.isDiseaseCertificateEnabled = !0);
                t.resolve(!0)
            }), t.promise
        },
        dt = function() {
            var t = e.open({
                animation: !0,
                backdrop: "static",
                template: "<emr-custom-template-view><\/emr-custom-template-view>",
                controller: "EmrCustomTemplateCtrl",
                windowClass: "transaction-code-dialog",
                resolve: {
                    host: function() {
                        return {
                            patientId: n.patientId
                        }
                    }
                }
            });
            t.result.then(function(n) {
                n && n.templateId > 0 && ct(n.id).then(function() {
                    ht()
                })
            })
        },
        ct = function(t) {
            var i = e.open({
                animation: !0,
                backdrop: "static",
                template: "<document-edit-dialog-view><\/document-edit-dialog-view>",
                controller: "DocumentEditDialogCtrl",
                windowClass: "stockout-detail-dialog",
                size: "lg",
                resolve: {
                    host: function() {
                        return {
                            patientId: n.patientId,
                            documentId: t,
                            documentType: o.DocumentType.EmrDocument
                        }
                    }
                }
            });
            return i.result
        },
        gt = function(t) {
            var i = e.open({
                animation: !0,
                backdrop: "static",
                template: "<document-print-dialog-view><\/document-print-dialog-view>",
                controller: "DocumentPrintDialogCtrl",
                windowClass: "xl-dialog",
                size: "lg",
                resolve: {
                    host: function() {
                        return {
                            patientId: n.patientId,
                            documentId: t
                        }
                    }
                }
            });
            return i.result
        },
        lt = function() {
            var t = n.searchCriteria.text.trim(),
                i = n.searchCriteria.archive.trim(),
                o, r, s, f, h, c, u, e, l;
            if (i = i == ft ? "" : i, n.searchCount = 0, n.searchCriteria.toothArray.length > 0 || t || i) {
                if (o = angular.copy(n.copyMedicalRecords), r = [], (t || i) && (t && i ? r = _.filter(o, function(n) {
                        return n.title.indexOf(t) > -1 && n.archive.indexOf(i) > -1 || n.content.indexOf(t) > -1
                    }) : t ? r = _.filter(o, function(n) {
                        return n.title.indexOf(t) > -1 || n.content.indexOf(t) > -1
                    }) : i && (r = _.filter(o, function(n) {
                        return n.archive.indexOf(i) > -1
                    })), angular.forEach(r, function(n) {
                        var r = '<span class="color-red">' + t + "<\/span>",
                            u;
                        t && n.title.indexOf(t) > -1 && (n.title = n.title.replace(t, r));
                        i && n.title.indexOf(i) > -1 && t != i && (u = '<span class="color-red">' + i + "<\/span>", n.title = n.title.replace(i, u));
                        t && n.content.indexOf(t) > -1 && (n.content = n.content.replace(t, r))
                    })), s = r.length > 0, f = [], n.searchCriteria.toothArray.length > 0)
                    for (u = angular.copy(_.filter(n.copyMedicalRecords, {
                            isDocument: !1
                        })), r = s ? r : u, h = 0; h < n.searchCriteria.toothArray.length; h++)
                        if (c = n.searchCriteria.toothArray[h], u = _.filter(r, function(n) {
                                return n.toothCode.indexOf(c) > -1
                            }), u && u.length > 0)
                            for (e = 0; e < u.length; e++) l = _.find(f, function(n) {
                                return n.id == u[e].id
                            }), l || f.push(u[e]);
                r = f.length > 0 ? f : s && n.searchCriteria.toothArray.length == 0 ? r : [];
                t == "" && i == "" || s || (r = []);
                et(r);
                n.medicalRecords = r;
                n.searchCount = r.length
            } else n.medicalRecords = angular.copy(n.copyMedicalRecords)
        },
        et = function(t) {
            var r = !1,
                u = !1,
                f = !1,
                e = !1,
                i = [{
                    name: ft
                }];
            angular.forEach(t, function(o) {
                var s, h, v, c, y, a, b;
                o.className = "detail" + o.id;
                o.color = "#00A8CB";
                o.startTimeStr = moment(o.startTime).format("YYYY-MM-DD HH:mm");
                o.isDocument || (s = _.find(n.providers, function(n) {
                    return n.id == o.doctorId
                }), o.doctorName = s ? s.name : "", o.department = s ? s.department : "");
                o.name || o.content && (h = o.content.split("："), h.length > 0 && (o.name = h[0] + "：", o.content = h[1]));
                o.archive = o.archive ? o.archive : "";
                !n.archives && o.title && (v = o.title.indexOf("标签："), v > -1 && (c = o.title.substr(v + 3), o.archive = c, y = _.find(i, function(n) {
                    return n.name == c
                }), y || i.push({
                    name: c
                })));
                var l = moment(o.startTimeStr),
                    k = moment(Ares.today()).format("YYYY-MM-DD"),
                    tt = moment(Ares.today()).startOf("month"),
                    p = moment(Ares.today()).add(-30, "d"),
                    w = moment(Ares.today()).add(-180, "d"),
                    d = moment(Ares.today()).startOf("year"),
                    g = moment(p).format("YYYY") == moment(Ares.today()).format("YYYY"),
                    nt = moment(w).format("YYYY") == moment(Ares.today()).format("YYYY");
                k == o.startTimeStr ? r ? (o.dateStr = null, o.tag = "今日") : (o.dateStr = "今日", o.tag = "今日", r = !0) : l >= p && g ? u ? (o.dateStr = null, o.tag = "一个月") : (o.dateStr = "一个月", o.tag = "一个月", u = !0) : l >= w && nt ? f ? (o.dateStr = null, o.tag = "半年") : (o.dateStr = "半年", o.tag = "半年", f = !0) : l >= d ? e ? (o.dateStr = null, o.tag = "今年") : (o.dateStr = "今年", o.tag = "今年", e = !0) : (a = moment(l).format("YYYY") + "年", b = _.find(t, function(n) {
                    return n.dateStr == a
                }), o.dateStr = b ? null : a, o.tag = a, o.color = "#9397A2");
                o.dateStr && (n.lastEmrTag = o.dateStr)
            });
            n.archives = n.archives ? n.archives : i
        },
        ni = function() {
            var t = r.defer();
            return a.doctorDic.load().then(function(i) {
                n.providers = i;
                t.resolve(!0)
            }), t.promise
        },
        ut = function(n) {
            for (var t = 0; t < n.length; t++) n[t].fdiToothCodeArray = angular.copy(n[t].fdiToothCodes)
        },
        ot = function(t, i, u) {
            var f = r.defer();
            return t != null ? t.isDocument ? (gt(t.medicalRecordId), f.resolve()) : t.isShowDetail ? (u || (t.isShowDetail = !1), f.resolve(t)) : t.hasDetailData ? (u || (t.isShowDetail = !0), n.setHeight(t), f.resolve(t)) : c.getFullMedicalRecord(t.medicalRecordId).success(function(r) {
                t.hasDetailData = !0;
                t.chiefComplaint = r.chiefComplaint;
                t.layoutTemplateCode = r.layoutTemplateCode;
                t.oralCheckRecordList = r.oralCheckRecordList;
                t.radiologyCheckRecordList = r.radiologyCheckRecordList;
                t.diagnoseRecordList = r.diagnoseRecordList;
                t.treatmentPlanList = r.treatmentPlanList;
                t.cureRecordList = r.cureRecordList;
                t.treatmentAdviceList = r.treatmentAdviceList;
                t.fieldList = r.fieldList;
                t.associatedImageList = r.associatedImageList;
                ut(t.oralCheckRecordList);
                ut(t.radiologyCheckRecordList);
                ut(t.diagnoseRecordList);
                ut(t.treatmentPlanList);
                ut(t.cureRecordList);
                ut(t.treatmentAdviceList);
                it.formatMedicalRecordFields(t);
                t.advice = r.advice;
                t.nurseName = r.nurseName;
                t.pastHistory = r.pastHistory;
                t.history = r.history;
                t.firstVisit = r.firstVisit;
                t.appointDateTime = r.appointDateTime;
                t.comment = r.comment;
                t.planPrice = r.planPrice;
                u || (t.isShowDetail = i >= 0 ? !1 : !0);
                t.apptId = r.appointId;
                t.imageId = r.imageId;
                t.patientDocumentId = r.patientDocumentId;
                t.generalExamId = r.generalExamId;
                t.perioExam = r.perioExam;
                t.outProcessorderId = r.outProcessorderId;
                t.followupId = r.followupId;
                t.chargeOrderTagId = r.chargeOrderTagId;
                t.drugorderId = r.drugorderId;
                t.doctorName = r.doctorName;
                n.setHeight(t);
                var e = a.officeDic.getItemSync(r.officeId);
                e && (t.officeName = e.abbreviation);
                n.clickEmrCount = n.clickEmrCount + 1;
                ti(t);
                t.employeeSignature = _.find(n.providerPictures, function(n) {
                    return r.doctorId == n.providerId
                });
                f.resolve(t)
            }) : f.resolve(), f.promise
        },
        ti = function(n) {
            n.layoutTemplateCode || (n.layoutTemplateCode = n.firstVisit ? rt.firstVisitTemplateCode : rt.secondVisitTemplateCode)
        },
        ii = function(t, i) {
            y.isAllowed("patientMedicalRecord.delete") ? t.isDocument ? s.confirm("提醒", "确定删除此病例文档？").then(function() {
                b.deleteDocument(t.medicalRecordId).success(function() {
                    n.medicalRecords.splice(i, 1);
                    h.success("删除成功")
                }).error(function(n) {
                    u.error(n)
                })
            }) : t.isAllowEdit == 1 ? at(t, i) : t.isAllowEdit == 2 ? s.info("提醒", "该病历超出病历时限范围，不允许删除！") : c.isAllowEditMedicalRecordByTimeLimit(t.medicalRecordId).success(function(n) {
                n ? (t.isAllowEdit = 1, at(t, i)) : (t.isAllowEdit = 2, s.info("提醒", "该病历超出病历时限范围，不允许删除！"))
            }) : s.info("提醒", "当前用户没有权限删除该病历！")
        },
        at = function(t, i) {
            s.confirm("提醒", "确定要删除此病历记录？").then(function() {
                c.deleteMedicalRecord(t.medicalRecordId).success(function() {
                    n.medicalRecords.splice(i, 1);
                    et(n.medicalRecords);
                    h.success("删除成功")
                }).error(function(n) {
                    h.success("删除失败");
                    u.log(n)
                })
            })
        },
        ri = function() {
            var n = e.open({
                animation: !0,
                backdrop: "static",
                template: "<emr-print-configuration-view><\/emr-print-configuration-view>",
                controller: "emrPrintConfigurationCtrl",
                size: "lg",
                resolve: {
                    host: function() {
                        return {
                            template: "emr"
                        }
                    }
                }
            });
            n.result.then(function(n) {
                st(n)
            })
        },
        st = function(t) {
            n.date = new Date;
            n.printTemplateConfig = {
                configName: "emr",
                coments: "emrPrint"
            };
            var i = t && t.configName == "emr" ? r.when(t.configValue) : p.getConfigValue("emr");
            i.then(function(t) {
                if (t && t != "") {
                    var i = t;
                    n.printTemplateConfig.isHide = !1;
                    n.printTemplateConfig.templateCode = i;
                    i.indexOf("EMR") < 0 && (n.printTemplateConfig.isHide = !0);
                    k.getTemplateByCode(i).then(function(t) {
                        n.printTemplate = t
                    })
                } else n.printTemplateConfig.isHide = !0
            })
        },
        ui = function() {
            var t = a.officeDic.getItemSync(v.officeId);
            n.office = t
        },
        fi = function() {
            var t = r.defer();
            return c.getLitePatient(n.patientId).success(function(i) {
                i.age = d.getPatientAge(i);
                n.patient = i;
                t.resolve(i)
            }), t.promise
        },
        ei = function(t) {
            var i = _.filter(n.medicalRecords, function(n) {
                    return n.tag == t.tag
                }),
                r = !t.isHide,
                f = i && r ? i.length : 0,
                u;
            angular.forEach(i, function(n, t) {
                n.isHide = r;
                n.tagCount = f;
                n.isHideTimeLine = t > 0 && r ? !0 : !1
            });
            u = _.filter(n.medicalRecords, function(n) {
                return !n.isHide
            });
            n.showMedicalRecordCount = u ? u.length : 0
        },
        oi = function() {
            p.getConfigValue(p.configKeys.AllowToothFDI).then(function(t) {
                n.allowToothFDI = t ? t : !1
            });
            p.getConfigValue(p.configKeys.IsEnableEMRLittleToothPrint).then(function(t) {
                n.allowLittleToothPrint = t ? t : !1
            })
        },
        si = function(t) {
            n.searchCriteria.archive = angular.copy(t.sender.element[0].value);
            lt()
        },
        hi = function() {
            var t = r.defer();
            return c.getBodyCheck(n.patientId).success(function(i) {
                n.bodyCheck = i;
                t.resolve(i)
            }), t.promise
        },
        ci = function() {
            var t = r.defer();
            return a.providerPictureDic.load().then(function(i) {
                var i = _.filter(i, function(n) {
                    return n.proivderPictureType == o.ProivderPictureType.Signature
                });
                n.providerPictures = i;
                t.resolve(i)
            }), t.promise
        };
    (function() {
        n.clickEmrCount = 1;
        n.createCustomEmr = dt;
        n.medicalRecordId = (i.params.medicalRecordId || 0) * 1;
        n.date = new Date;
        n.isDisableEMRBlankPrint = !1;
        p.getConfigValue(p.configKeys.IsDisableEMRBlankPrint).then(function(t) {
            n.isDisableEMRBlankPrint = t
        });
        n.patientId = f.patientId;
        n.showDetail = ot;
        n.toPrint = ri;
        n.deleteEMR = ii;
        n.onToggleEmr = ei;
        n.searchCriteria = {
            toothArray: [],
            text: "",
            archive: ft
        };
        n.search = lt;
        n.onArchiveSelected = si;
        n.openPatientDocEditDialog = ct;
        n.initPrintData = st;
        n.getAllMedicalRecordDetails = wt;
        n.bodyCheck = {};
        vt()
    })()
}]);
emrModule.controller("EmrCureRecordsEditCtrl", ["$log", "$q", "$scope", "aresNotification", "systemConfigUtil", "dataDicSvc", "generalExamSvc", "emrUtil", "chargeSvc", function(n, t, i, r, u, f, e, o, s) {
    "use strict";
    var h = function() {
        i.apptId && s.getDetailByAppointmentId(i.apptId).then(function(n) {
            var t, r;
            if (n.data) {
                for (t = 0; t < n.data.length; t++) r = [], n.data[t].fdiToothCodes && (r = n.data[t].fdiToothCodes.split(",")), o.cureRecordImport(r, n.data[t].itemName, i.currentValue);
                i.currentValue = _(i.currentValue).reject(function(n) {
                    return n.cure == "" && n.fdiToothCodesArray.length == 0
                })
            }
        })
    };
    (function() {
        i.importToCureRecord = h
    })()
}]);
emrModule.controller("EmrOralCheckRecordsEditCtrl", ["$log", "$q", "$scope", "aresNotification", "systemConfigUtil", "dataDicSvc", "generalExamSvc", "emrUtil", "chargeSvc", function(n, t, i, r, u, f, e, o) {
    "use strict";
    var s = function() {
        i.patientId && f.observationCodeDic.load().then(function() {
            e.getFullExam(i.patientId, Ares.today()).success(function(n) {
                for (var r, c, e, u, s, l, t = "", h = 0; h < n.teeth.length; h++)
                    if (r = n.teeth[h], !(r.observations.length < 1)) {
                        for (t = "", c = r.code, e = 0; e < r.observations.length; e++) u = r.observations[e], s = f.observationCodeDic.getItemSyncEx({
                            code: u.observationCode
                        }), s && (t = u.notes && u.observationCode == "notes" ? t + s.name + ":" + u.notes + "，" : t + s.name + "，");
                        if (t = t == "" ? t : t.substring(0, t.length - 1), o.oralCheckRecordImport(c, t, i.currentValue, i.IsAloneSaveOralCheckSymptom), i.onExamImporting) i.onExamImporting(c, t)
                    }
                l = _(i.currentValue).reject(function(n) {
                    return n.description == "" && n.fdiToothCodesArray.length == 0
                });
                l.length > 0 && (i.currentValue = l);
                i.onExamImported && i.onExamImported()
            }).error(function() {})
        })
    };
    (function() {
        i.importToothExamContent = s
    })()
}]);
emrModule.controller("EmrTreatmentPlansEditCtrl", ["$log", "$q", "$scope", "aresNotification", "systemConfigUtil", "dataDicSvc", "generalExamSvc", "emrUtil", "patientSvc", function(n, t, i, r, u, f, e, o, s) {
    "use strict";
    var h = function() {
        i.patientId && s.getTxPlanByPatientId(i.patientId).then(function(n) {
            for (var r, t = 0; t < n.data.length; t++) r = [], n.data[t].toothObservationCode && (r = n.data[t].toothObservationCode.split(",")), o.treatmentPlanImport(r, n.data[t].treatment, i.currentValue);
            i.currentValue = _(i.currentValue).reject(function(n) {
                return n.planContent == "" && n.fdiToothCodesArray.length == 0
            })
        })
    };
    (function() {
        i.importToTreatmentPlan = h
    })()
}]);
emrModule.controller("allMedicalrecordCtrl", ["$log", "$q", "$scope", "$modal", "$filter", "appNav", "constants", "enums", "patientSvc", "practiceSvc", "formatUtil", "shortMessageUtil", "aresDialog", "reportSvc", "dataDicSvc", "loginContext", "officeOptionSvc", "printTemplateUtil", "systemConfigUtil", "officeSvc", function(n, t, i, r, u, f, e, o, s, h, c, l, a, v, y, p, w) {
    "use strict";
    var k;
    i.medicalRecords = [];
    var b = function() {
            if (i.range == "自定义") {
                var n = Ares.today(),
                    t = moment(n).add(-1, "week").toDate();
                k = {
                    startDate: t,
                    endDate: n
                };
                i.timeSpan = _.clone(k)
            }
        },
        tt = function() {
            d();
            nt()
        },
        d = function() {
            var n = t.defer(),
                r;
            return i.isSearching = !0, r = g(), v.getMedicalrecord(r).success(function(t) {
                for (var r, s, e, h, o = u("toDateTimeString"), f = 0; f < t.items.length; f++) r = t.items[f], r.recordCreatedTime = o(r.recordCreatedTime), r.recordUpdatedTime = o(r.recordUpdatedTime), s = r.layoutTemplateCode, e = _.find(i.layoutTemplates, function(n) {
                    return n.templateCode == s
                }), r.templateName = e ? e.templateName : "";
                i.searchData = t;
                h = {
                    total: i.searchData.totalCount,
                    data: i.searchData.items
                };
                n.resolve(h)
            }).error(function() {
                i.isSearching = !1
            }), n.promise
        },
        g = function() {
            var t, r, u = i.range || $("#daysBeforeTodayInput").val(),
                n;
            return u == "自定义" ? (t = i.timeSpan.startDate, r = moment(i.timeSpan.endDate).add(1, "d")) : u == "week" ? (t = moment(Ares.today()).startOf("week"), r = moment(Ares.today()).add(1, "d")) : u == "month" ? (t = moment(Ares.today()).startOf("month"), r = moment(Ares.today()).add(1, "d")) : (t = moment(Ares.today()).add(-u, "d"), r = moment(Ares.today()).add(1, "d")), n = {}, i.pageIndex = i.pageIndex || 1, i.pageSize = i.pageSize || 10, n.doctorId = i.doctorId > 0 ? i.doctorId : -1, n.nurseId = i.nurseId > 0 ? i.nurseId : -1, n.department = i.department ? i.department : "全部", n.patientName = "", n.archive = $("#archiveInput").val() == "" ? "全部" : $("#archiveInput").val(), n.layoutTemplateCode = i.getTemplateDropDownValue(), n.startDate = moment(t).format("YYYY-MM-DD"), n.endDate = moment(r).format("YYYY-MM-DD"), n.pageIndex = i.pageIndex, n.pageSize = i.pageSize, n.sortField = i.sortField, n.sortRule = i.sortRule, localStorage.allMedicalrecord_daysBeforeTodayInput = u, localStorage.allMedicalrecord_startTime = t, localStorage.allMedicalrecord_endTime = moment(r).add(-1, "d"), localStorage.allMedicalrecord_doctorId = n.doctorId, localStorage.allMedicalrecord_nurseId = n.nurseId, localStorage.allMedicalrecord_department = n.department, localStorage.allMedicalrecord_archive = n.archive, localStorage.allMedicalrecord_templateCode = n.layoutTemplateCode, localStorage.allMedicalrecord_pageIndex = n.pageIndex, localStorage.allMedicalrecord_pageSize = n.pageSize, n
        },
        it = function(n, t) {
            l.sendMessage(n, t)
        },
        rt = function(n) {
            a.confirm("提醒", "确定要删除此患者的所有记录？").then(function() {
                s.deletePatient(n).success(function() {
                    a.info("信息", "删除成功！");
                    tt()
                }).error(function() {
                    a.warn("信息", "删除失败！")
                })
            })
        },
        nt = function() {
            i.office || h.getOffice(p.officeId).success(function(n) {
                i.office = n
            })
        },
        ft = function() {
            if (!i.patientId) return !1;
            s.getPatient(i.patientId).success(function(n) {
                var t, r, u;
                i.patient = n;
                i.patient && (i.patient.birth ? (t = moment(i.patient.birth, "YYYY-MM-DD"), t.isValid() || (t = moment(i.patient.birth, "YYYYMMDD")), t.isValid() && (r = moment(Ares.today()), u = r.diff(t, "years"), i.ignoreAgeChanged = !0, i.patient.age = u)) : i.patient.age = "")
            })
        },
        et = function(n) {
            for (var t = 0; t < n.length; t++) n[t].fdiToothCodeArray = angular.copy(n[t].fdiToothCodes)
        },
        ut = function() {
            var n = t.defer();
            return y.medicalRecordLayoutTemplateDic.load().then(function(t) {
                i.layoutTemplates = t;
                n.resolve()
            }), n.promise
        };
    (function() {
        i.getCriteria = g;
        i.range = "0";
        i.initDefaultTimeSpan = b;
        i.doctorId = localStorage.allMedicalrecord_doctorId ? localStorage.allMedicalrecord_doctorId : -1;
        i.archive = localStorage.allMedicalrecord_archive ? localStorage.allMedicalrecord_archive : "全部";
        i.nurseId = localStorage.allMedicalrecord_nurseId ? localStorage.allMedicalrecord_nurseId : -1;
        i.department = localStorage.allMedicalrecord_department ? localStorage.allMedicalrecord_department : "全部";
        localStorage.allMedicalrecord_pageIndex && (i.pageIndex = localStorage.allMedicalrecord_pageIndex, i.pageSize = localStorage.allMedicalrecord_pageSize);
        localStorage.allMedicalrecord_daysBeforeTodayInput ? (i.range = localStorage.allMedicalrecord_daysBeforeTodayInput, localStorage.allMedicalrecord_daysBeforeTodayInput == "自定义" && (localStorage.allMedicalrecord_startTime ? (b(), i.timeSpan.startDate = moment(localStorage.allMedicalrecord_startTime).format("YYYY-MM-DD"), i.timeSpan.endDate = moment(localStorage.allMedicalrecord_endTime).format("YYYY-MM-DD")) : b())) : b();
        i.sendMessage = it;
        i.deletePatient = rt;
        i.search = d;
        nt();
        i.initLayoutTemplates = ut;
        h.getSystemConfigByName("IsDisableEMRBlankPrint").success(function(n) {
            i.isDisableEMRBlankPrint = n.configValue == "true"
        });
        w.getOfficeOption(w.optionKeys.IsEmrCustomTemplateEnabled).then(function(n) {
            n == "1" && (i.isEmrCustomTemplateEnabled = !0)
        })
    })()
}]);
emrModule.controller("MedicalrecordHomeCtrl", ["$log", "$scope", "dataDicSvc", function() {
    "use strict";
    (function() {})()
}]);
emrModule.controller("MedicalrecordRejectionDialogCtrl", ["$log", "$timeout", "$q", "$scope", "$modalInstance", "host", "commonTaskSvc", function(n, t, i, r, u, f, e) {
    "use strict";
    var o = function(n) {
            var f = {
                    medicalRecordId: r.medicalRecordId,
                    reason: n.rejectReason,
                    action: "reject"
                },
                t = i.defer();
            return e.rejectMedicalRecordTask(f).success(function(n) {
                t.resolve(n);
                u.close(n)
            }), t.promise
        },
        s = function() {
            u.close()
        },
        h = function() {
            r.medicalRecordId > 0 && r.action === "readonly" ? e.getTaskByMedicalRecordId(r.medicalRecordId).then(function(n) {
                n && n.data && (r.taskObj = {
                    rejectReason: n.data.notes,
                    rejectTime: n.data.taskUpdateTime,
                    rejectUser: n.data.taskUpdateUserName
                })
            }) : r.taskObj = {
                rejectReason: "",
                rejectTime: "",
                rejectUser: ""
            }
        };
    (function() {
        r.taskObj = {};
        r.medicalRecordId = f.medicalRecordId;
        r.action = f.action || "edit";
        r.cancel = s;
        r.save = o;
        h()
    })()
}]);
emrModule.controller("NotwritingMedicalrecordDialogCtrl", ["$log", "$timeout", "$q", "$scope", "$modalInstance", "host", "commonTaskSvc", function(n, t, i, r, u, f, e) {
    "use strict";
    var o = function(n) {
            var r = {
                    taskId: f.taskId,
                    notes: n
                },
                t = i.defer();
            return e.ignore(r).success(function(n) {
                t.resolve(n);
                u.close(n)
            }), t.promise
        },
        s = function() {
            u.close()
        };
    (function() {
        r.cancel = s;
        r.save = o
    })()
}]);
emrModule.controller("notwritingMedicalrecordCtrl", ["$log", "$scope", "$modal", "$q", "$filter", "localCache", "appNav", "moduleOptionProvider", "constants", "enums", "patientSvc", "formatUtil", "shortMessageUtil", "aresDialog", "commonTaskSvc", "officeOptionSvc", "officeSvc", "dataDicSvc", function(n, t, i, r, u, f, e, o, s, h, c, l, a, v, y, p, w, b) {
    "use strict";
    var nt = f.getCache(f.keys.NotwritingMedicalrecordCriteria),
        d, k = function() {
            var n = Ares.today(),
                i = moment(n).add(-1, "week").toDate();
            d = {
                startDate: i,
                endDate: n
            };
            t.timeSpan = _.clone(d)
        },
        tt = function() {
            var n = r.defer(),
                i = g();
            return y.getNotWritingMedicalrecord(i).success(function(i) {
                _.each(i.items, function(n) {
                    n.startTimeSource = n.startTime;
                    n.startTime = u("toDateTimeString")(n.startTime);
                    n.isFirstVisit = u("toFirstVisit")(n.isFirstVisit);
                    var r = n.layoutTemplateCode,
                        i = _.find(t.layoutTemplates, function(n) {
                            return n.templateCode == r
                        });
                    n.templateName = i ? i.templateName : ""
                });
                t.searchResult = i;
                n.resolve(i)
            }).error(function() {
                t.isSearching = !1;
                n.reject()
            }), n.promise
        },
        g = function() {
            var n = {},
                i, r, u = t.range || $("#daysBeforeTodayInput").val(),
                f;
            return u == "自定义" ? (i = t.timeSpan.startDate, r = moment(t.timeSpan.endDate).add(1, "d")) : u == "week" ? (i = moment(Ares.today()).startOf("week"), r = moment(Ares.today()).add(1, "d")) : u == "month" ? (i = moment(Ares.today()).startOf("month"), r = moment(Ares.today()).add(1, "d")) : u == "yesterday" ? (i = moment(Ares.today()).add(-1, "d"), r = moment(Ares.today())) : (i = moment(Ares.today()).add(-u, "d"), r = moment(Ares.today()).add(1, "d")), n.doctorId = t.doctorId > 0 ? t.doctorId : -1, n.department = t.department ? t.department : "全部", n.medicalRecordStatus = t.medicalRecordStatus >= 0 ? t.medicalRecordStatus : -1, n.apptConsultState = t.apptConsultState >= 0 ? t.apptConsultState : -1, f = t.getTemplateDropDownValue(), t.isSearching = !0, n.emrType = t.emrType, n.pageIndex = t.pageIndex, n.pageSize = t.pageSize, n.startDate = moment(i).format("YYYY-MM-DD"), n.endDate = moment(r).format("YYYY-MM-DD"), n.layoutTemplateCode = f, nt.saveObject({
                nowritingemr_daysBeforeTodayInput: u,
                nowritingemr_startTime: i,
                nowritingemr_endTime: moment(r).add(-1, "d"),
                nowritingemr_doctorId: n.doctorId,
                nowritingemr_department: n.department,
                nowritingemr_medicalRecordStatus: n.medicalRecordStatus,
                nowritingemr_apptConsultState: n.apptConsultState,
                nowritingemr_templateCode: f
            }), n.medicalRecordStatus === 10 ? (n.medicalRecordStatus = 0, n.taskType = 3) : n.medicalRecordStatus === 11 ? (n.medicalRecordStatus = 1, n.taskType = 3) : n.taskType = 1, n
        },
        it = function() {
            p.isStrongStrictAllowed().then(function(n) {
                t.isStrongStrict = n
            })
        },
        rt = function(n) {
            t.apptConsultState = n.nowritingemr_apptConsultState ? n.nowritingemr_apptConsultState : -1;
            t.doctorId = n.nowritingemr_doctorId ? n.nowritingemr_doctorId : -1;
            t.medicalRecordStatus = n.nowritingemr_medicalRecordStatus ? n.nowritingemr_medicalRecordStatus : -1;
            t.department = n.nowritingemr_department ? n.nowritingemr_department : -1;
            n.nowritingemr_daysBeforeTodayInput ? (t.range = n.nowritingemr_daysBeforeTodayInput, n.nowritingemr_daysBeforeTodayInput == "自定义" ? n.nowritingemr_startTime ? (k(), t.timeSpan.startDate = moment(n.nowritingemr_startTime).format("YYYY-MM-DD"), t.timeSpan.endDate = moment(n.nowritingemr_endTime).format("YYYY-MM-DD")) : k() : k()) : k()
        },
        ut = function() {
            var n = r.defer();
            return b.medicalRecordLayoutTemplateDic.load().then(function(i) {
                t.layoutTemplates = i;
                n.resolve()
            }), n.promise
        };
    (function() {
        it();
        t.isStrongStrict = !1;
        t.range = "0";
        t.initLayoutTemplates = ut;
        t.isDelunCustomFeatureOpen = o.isDelunCustomFeatureOpen();
        t.initDefaultTimeSpan = k;
        t.initSearchCriteria = rt;
        t.searchMedicalRecords = tt;
        t.getSearchCriteria = g
    })()
}]);
emrModule.directive("emrPrintCompile", ["$compile", "practiceSvc", "printTemplateUtil", function(n, t, i) {
    "use strict";
    return {
        replace: !0,
        restrict: "EA",
        link: function(t, r, u) {
            var o = {
                    $destroy: angular.noop
                },
                s = r,
                f, e = function() {
                    (f || o).$destroy()
                };
            u.$observe("htmlContent", function(r) {
                var u, o;
                r && (e(), f = t.$new(!1), u = n(r)(f), s.html(u), o = t.printTemplateConfig.templateCode, i.getTemplateByCode(o).then(function(n) {
                    var i;
                    if (n && n.isPrivateTemplate) {
                        typeof t.initPictrue == "function" && t.initPictrue(n);
                        var r = 0,
                            f = 0,
                            u = 50,
                            e = 0;
                        n && n.templateStyle != null && (i = n.templateStyle.split(","), i.length == 4 && (r = i[0], f = i[1], u = i[2], e = i[3]));
                        u = t.isEmrCustomTemplateEnabled ? 75 : u;
                        r = t.isEmrCustomTemplateEnabled ? 10 : r;
                        $("#" + n.templateCode + " #templateBody").css("margin", "" + r + "px " + e + "px " + f + "px " + u + "px");
                        t.privateTemplate = n
                    }
                }));
                t.$on("$destroy", e)
            })
        }
    }
}]);
emrModule.directive("emrTablePrintTemplate", ["$log", "$timeout", "pictureSvc", "practiceSvc", "$filter", "$sce", "toothUtil", "systemConfigSvc", function(n, t, i, r, u, f, e) {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/emr/emr-print/emr-table-print-template.html",
        link: function(n) {
            var r = Ares.MergeField,
                s = [],
                h = function(t) {
                    var r = "",
                        i;
                    if (t)
                        for (i = 0; i < t.length; i++) {
                            var u = t[i],
                                f = u.fdiToothCodes || "",
                                e = 15;
                            n.allowToothFDI || (f = o(u), e = 50);
                            r = r + '<div style="min-height: ' + e + 'px;">' + f + u.description + "<\/div>"
                        }
                    return r
                },
                l = function(t) {
                    var r = "",
                        i;
                    if (t)
                        for (i = 0; i < t.length; i++) {
                            var u = t[i],
                                f = u.fdiToothCodes || "",
                                e = 15;
                            n.allowToothFDI || (f = o(u), e = 50);
                            r = r + '<div style="min-height:  ' + e + 'px;">' + f + u.diagnose + "<\/div>"
                        }
                    return r
                },
                a = function(t) {
                    var r = "",
                        i;
                    if (t)
                        for (i = 0; i < t.length; i++) {
                            var u = t[i],
                                f = u.fdiToothCodes || "",
                                e = 15;
                            n.allowToothFDI || (f = o(u), e = 50);
                            r = r + '<div style="min-height: ' + e + 'px;">' + f + u.planContent + "<\/div>"
                        }
                    return r
                },
                v = function(t) {
                    var r = "",
                        i;
                    if (t)
                        for (i = 0; i < t.length; i++) {
                            var u = t[i],
                                f = u.fdiToothCodes || "",
                                e = 15;
                            n.allowToothFDI || (f = o(u), e = 50);
                            r = r + '<div style="min-height: ' + e + 'px;">' + f + u.content + "<\/div>"
                        }
                    return r
                },
                y = function(t) {
                    var r = "",
                        i;
                    if (t)
                        for (i = 0; i < t.length; i++) {
                            var u = t[i],
                                f = u.fdiToothCodes || "",
                                e = 15;
                            n.allowToothFDI || (f = o(u), e = 50);
                            r = r + '<div style="min-height:  ' + e + 'px;">' + f + u.cure + "<\/div>"
                        }
                    return r
                },
                o = function(t) {
                    var r = [
                            [],
                            [],
                            [],
                            []
                        ],
                        u, s, f, o, i;
                    return t.fdiToothCodes && (t.fdiToothCodeArray = _.isArray(t.fdiToothCodes) ? t.fdiToothCodes : t.fdiToothCodes.split(","), u = _.map(t.fdiToothCodeArray, function(n) {
                        return e.getTooth(n)
                    }), u = _.compact(u), s = u.sort(e.compareTooth), angular.forEach(s, function(n) {
                        var t = n.getQuadrant(),
                            i = n.getQuadrantCode();
                        r[t - 1].push(i)
                    })), t.quadrant1Text = r[0].reverse().join(""), t.quadrant2Text = r[1].join(""), t.quadrant3Text = r[2].join(""), t.quadrant4Text = r[3].reverse().join(""), f = !0, o = !0, f = t.quadrant1Text || t.quadrant2Text ? !0 : !1, o = t.quadrant3Text || t.quadrant4Text ? !0 : !1, n.allowLittleToothPrint ? (i = '<table style="border-collapse: collapse; height: 20px;float: left;margin-right: 5px;"><tr class="tooth-selector-upper-arch">', f && (i += '<td id="quadrant1" style="font-size:12px;border-bottom:1px solid gray;text-align: right; border-right: 1px solid gray; width: 55px; max-width: 70px;">' + t.quadrant1Text + '<\/td><td style="font-size:12px;border-bottom:1px solid gray;width: 55px; max-width: 70px;" id="quadrant2">' + t.quadrant2Text + "<\/td>"), o && (i += '<td id="quadrant4"  style="font-size:12px;border-top:1px solid gray;text-align: right; border-right: 1px solid gray; width: 55px; max-width: 70px;">' + t.quadrant4Text + '<\/td><td style="font-size:12px;border-top:1px solid gray;width: 55px; max-width: 70px;" id="quadrant3">' + t.quadrant3Text + "<\/td>"), i += "<\/tr><\/table>") : i = '<table style="border-collapse: collapse; height: 20px;float: left;margin-right: 5px;"><tr style="border-bottom:1px solid gray" class="tooth-selector-upper-arch"><td id="quadrant1" style="text-align: right; border-right: 1px solid gray; width: 70px; max-width: 70px;">' + t.quadrant1Text + '<\/td><td style="width: 70px; max-width: 70px;" id="quadrant2">' + t.quadrant2Text + '<\/td><\/tr><tr class="tooth-selector-lower-arch"><td id="quadrant4" style="text-align: right; border-right: 1px solid gray; width: 70px; max-width: 70px;">' + t.quadrant4Text + '<\/td><td style="width: 70px; max-width: 70px;" id="quadrant3">' + t.quadrant3Text + "<\/td><\/tr><\/table>", i
                },
                p = function(t) {
                    var e, o, c;
                    n.patient && (n.patient.birth ? (e = moment(n.patient.birth, "YYYY-MM-DD"), e.isValid() || (e = moment(n.patient.birth, "YYYYMMDD")), e.isValid() && (o = moment(Ares.today()), c = o.diff(e, "years"), n.ignoreAgeChanged = !0, n.age = c)) : n.age = "");
                    var i = t,
                        f = n.bodyCheck,
                        w = h(i.oralCheckRecordList) || "",
                        k = h(i.radiologyCheckRecordList) || "",
                        d = l(i.diagnoseRecordList) || "",
                        g = a(i.treatmentPlanList) || "",
                        nt = v(i.treatmentAdviceList) || "",
                        tt = y(i.cureRecordList) || "",
                        it = b(i.employeeSignature),
                        p = "初诊";
                    i.firstVisit || (p = "复诊");
                    s = [new r("{患者姓名}", n.patient.name || ""), new r("{病历号}", n.patient.privateId || ""), new r("{性别}", u("toSexString")(n.patient.sex)), new r("{出生年月日}", u("toDateString")(n.patient.birth)), new r("{就诊日期}", u("toDateString")(i.appointDateTime)), new r("{医生}", i.doctorName || ""), new r("{护士}", i.nurseName || ""), new r("{主诉}", i.chiefComplaint || ""), new r("{现病史}", i.history || ""), new r("{既往史}", i.pastHistory || ""), new r("{口腔检查}", w), new r("{辅助检查}", k), new r("{相关影像}", ""), new r("{诊断}", d), new r("{治疗计划}", g), new r("{治疗建议}", nt), new r("{处置}", tt), new r("{医嘱}", i.advice || ""), new r("{备注}", i.comment || ""), new r("{打印日期}", u("toDateString")(Ares.today())), new r("{诊所地址}", n.office ? n.office.address : ""), new r("{联系电话}", n.office ? n.office.phoneNumber : ""), new r("{诊所名}", n.office ? n.office.name : ""), new r("{病历类型}", p), new r("{患者手机号码}", n.patient.mobile || ""), new r("{患者既往史}", f === null ? "" : f.disease), new r("{患者过敏史}", f === null ? "" : f.medicine), new r("{患者用药史}", f === null ? "" : f.medicineNow), new r("{医生签字}", it), ];
                    n.templatePicture && s.push(new r("{URL}", n.templatePicture.filePath))
                },
                w = function(t) {
                    t.pictureId > 0 ? i.getPicture(t.pictureId).success(function(i) {
                        n.templatePicture = i;
                        c(t)
                    }) : c(t)
                },
                c = function(t) {
                    for (var u, i, r = 0; r < n.medicalRecords.length; r++) u = n.medicalRecords[r], i = t.templateContent, p(u), i = i.replace(/[\[]/g, "{"), i = i.replace(/]/g, "}"), angular.forEach(s, function(n) {
                        i = n.translate(i)
                    }), u.printTemplate = f.trustAsHtml(i)
                },
                b = function(n) {
                    return n && n.picture && n.picture.filePath ? '<img style="vertical-align: middle;" width="150" height="80" src = "' + n.picture.filePath + '"/>"' : "___________"
                },
                k = function() {
                    var i = n.printTemplate,
                        r, s;
                    if (i) {
                        i.isPrivateTemplate && (w(i), n.privateTemplate = n.printTemplate);
                        var u = 0,
                            e = 0,
                            f = 50,
                            o = 0;
                        i.templateStyle && (r = i.templateStyle.split(","), r.length == 4 && (u = r[0], e = r[1], f = r[2], o = r[3]));
                        f = n.isEmrCustomTemplateEnabled ? 75 : f;
                        u = n.isEmrCustomTemplateEnabled ? 10 : u;
                        s = "" + u + "px " + o + "px " + e + "px " + f + "px";
                        t(function() {
                            $("#" + i.templateCode + " #templateBody").css("margin", s)
                        }, 500)
                    }
                };
            (function() {
                n.refreshTemplate = k
            })()
        }
    }
}]);
emrModule.directive("newEmrPrintTemplate", ["$log", "$timeout", "pictureSvc", "practiceSvc", "$filter", "$sce", "toothUtil", function(n, t, i, r, u, f, e) {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/emr/emr-print/new-emr-print-template.html",
        link: function(n) {
            var r = Ares.MergeField,
                s = [],
                h = function(t) {
                    var r = "",
                        i;
                    if (t)
                        for (i = 0; i < t.length; i++) {
                            var u = t[i],
                                f = u.fdiToothCodes || "",
                                e = 15;
                            n.allowToothFDI || (f = o(u), e = 50);
                            r = r + '<div style="min-height: ' + e + 'px;">' + f + u.description + "<\/div>"
                        }
                    return r
                },
                a = function(t) {
                    var r = "",
                        i;
                    if (t)
                        for (i = 0; i < t.length; i++) {
                            var u = t[i],
                                f = u.fdiToothCodes || "",
                                e = 15;
                            n.allowToothFDI || (f = o(u), e = 50);
                            r = r + '<div style="min-height:  ' + e + 'px;">' + f + u.diagnose + "<\/div>"
                        }
                    return r
                },
                v = function(t) {
                    var r = "",
                        i;
                    if (t)
                        for (i = 0; i < t.length; i++) {
                            var u = t[i],
                                f = u.fdiToothCodes || "",
                                e = 15;
                            n.allowToothFDI || (f = o(u), e = 50);
                            r = r + '<div style="min-height: ' + e + 'px;">' + f + u.planContent + "<\/div>"
                        }
                    return r
                },
                y = function(t) {
                    var r = "",
                        i;
                    if (t)
                        for (i = 0; i < t.length; i++) {
                            var u = t[i],
                                f = u.fdiToothCodes || "",
                                e = 15;
                            n.allowToothFDI || (f = o(u), e = 50);
                            r = r + '<div style="min-height:  ' + e + 'px;">' + f + u.cure + "<\/div>"
                        }
                    return r
                },
                o = function(t) {
                    var r = [
                            [],
                            [],
                            [],
                            []
                        ],
                        o, s, u, f, i;
                    return t.fdiToothCodes && (t.fdiToothCodeArray = _.isArray(t.fdiToothCodes) ? t.fdiToothCodes : t.fdiToothCodes.split(","), o = _.map(t.fdiToothCodesArray, function(n) {
                        return e.getTooth(n)
                    }), s = o.sort(e.compareTooth), angular.forEach(s, function(n) {
                        if (n !== null) {
                            var t = n.getQuadrant(),
                                i = n.getQuadrantCode();
                            r[t - 1].push(i)
                        }
                    })), t.quadrant1Text = r[0].reverse().join(""), t.quadrant2Text = r[1].join(""), t.quadrant3Text = r[2].join(""), t.quadrant4Text = r[3].reverse().join(""), u = !0, f = !0, u = t.quadrant1Text || t.quadrant2Text ? !0 : !1, f = t.quadrant3Text || t.quadrant4Text ? !0 : !1, n.allowLittleToothPrint ? (i = '<table style="border-collapse: collapse; height: 20px;float: left;margin-right: 5px;"><tr class="tooth-selector-upper-arch zidingyi">', u && (i += '<td id="quadrant1" style="font-size:12px;border-bottom:1px solid gray;text-align: right; border-right: 1px solid gray; width: 55px; max-width: 70px;">' + t.quadrant1Text + '<\/td><td style="font-size:12px;border-bottom:1px solid gray;width: 55px; max-width: 70px;" id="quadrant2">' + t.quadrant2Text + "<\/td>"), f && (i += '<td id="quadrant4"  style="font-size:12px;border-top:1px solid gray;text-align: right; border-right: 1px solid gray; width: 55px; max-width: 70px;">' + t.quadrant4Text + '<\/td><td style="font-size:12px;border-top:1px solid gray;width: 55px; max-width: 70px;" id="quadrant3">' + t.quadrant3Text + "<\/td>"), i += "<\/tr><\/table>") : i = '<table style="border-collapse: collapse; height: 20px;float: left;margin-right: 5px;"><tr style="border-bottom:1px solid gray" class="tooth-selector-upper-arch"><td id="quadrant1" style="text-align: right; border-right: 1px solid gray; width: 70px; max-width: 70px;">' + t.quadrant1Text + '<\/td><td style="width: 70px; max-width: 70px;" id="quadrant2">' + t.quadrant2Text + '<\/td><\/tr><tr class="tooth-selector-lower-arch"><td id="quadrant4" style="text-align: right; border-right: 1px solid gray; width: 70px; max-width: 70px;">' + t.quadrant4Text + '<\/td><td style="width: 70px; max-width: 70px;" id="quadrant3">' + t.quadrant3Text + "<\/td><\/tr><\/table>", i
                },
                p = function() {
                    var f, e, o;
                    if (n.patient) {
                        n.patient.birth ? (f = moment(n.patient.birth, "YYYY-MM-DD"), f.isValid() || (f = moment(n.patient.birth, "YYYYMMDD")), f.isValid() && (e = moment(Ares.today()), o = e.diff(f, "years"), n.ignoreAgeChanged = !0, n.age = o)) : n.age = "";
                        var t = n.currentMedicalRecord,
                            i = n.bodyCheck,
                            e = Ares.today(),
                            l = h(t.oralCheckRecordList) || "",
                            p = h(t.radiologyCheckRecordList) || "",
                            w = a(t.diagnoseRecordList) || "",
                            k = v(t.treatmentPlanList) || "",
                            d = y(t.cureRecordList) || "",
                            g = b(n.hasEmployeeSignature, n.providerEmployeeSignature),
                            c = "初诊";
                        t.firstVisit || (c = "复诊");
                        s = [new r("{患者姓名}", n.patient.name || ""), new r("{病历号}", n.patient.privateId || ""), new r("{性别}", u("toSexString")(n.patient.sex)), new r("{出生年月日}", u("toDateString")(n.patient.birth)), new r("{就诊日期}", u("toDateString")(t.appointDateTime)), new r("{医生}", t.doctorName || ""), new r("{护士}", t.nurseName || ""), new r("{主诉}", t.chiefComplaint || ""), new r("{现病史}", t.history || ""), new r("{既往史}", t.pastHistory || ""), new r("{口腔检查}", l), new r("{辅助检查}", p), new r("{诊断}", w), new r("{治疗计划}", k), new r("{处置}", d), new r("{医嘱}", t.advice || ""), new r("{备注}", t.comment || ""), new r("{打印日期}", u("toDateString")(e)), new r("{诊所地址}", n.office.address), new r("{联系电话}", n.office.phoneNumber), new r("{诊所名}", n.office.name), new r("{病历类型}", c), new r("{患者手机号码}", n.patient.mobile), new r("{患者既往史}", i === null ? "" : i.disease), new r("{患者过敏史}", i === null ? "" : i.medicine), new r("{患者用药史}", i === null ? "" : i.medicineNow), new r("{医生签字}", g), ];
                        n.templatePicture && s.push(new r("{URL}", n.templatePicture.filePath))
                    }
                },
                w = function(t) {
                    t.pictureId > 0 ? i.getPicture(t.pictureId).success(function(i) {
                        n.templatePicture = i;
                        c(t)
                    }) : c(t)
                },
                c = function(n) {
                    var t = n.templateContent;
                    p();
                    t = t.replace(/[\[]/g, "{");
                    t = t.replace(/]/g, "}");
                    angular.forEach(s, function(n) {
                        t = n.translate(t)
                    });
                    n.printTemplate = f.trustAsHtml(t)
                },
                l = function() {
                    var i = n.printTemplate,
                        r, s;
                    if (i) {
                        i.isPrivateTemplate && (w(i), n.privateTemplate = n.printTemplate);
                        var u = 0,
                            e = 0,
                            f = 50,
                            o = 0;
                        i.templateStyle && (r = i.templateStyle.split(","), r.length == 4 && (u = r[0], e = r[1], f = r[2], o = r[3]));
                        f = n.isEmrCustomTemplateEnabled ? 75 : f;
                        u = n.isEmrCustomTemplateEnabled ? 10 : u;
                        s = "" + u + "px " + o + "px " + e + "px " + f + "px";
                        t(function() {
                            $("#" + i.templateCode + " #templateBody").css("margin", s)
                        }, 500)
                    }
                },
                b = function(n, t) {
                    return n && t ? "<img style='width:150px;vertical-align: middle;' src = '" + t.filePath + "'/>" : "___________"
                };
            (function() {
                n.$watch("printTemplate", function() {
                    l()
                });
                n.$on("medicalRecordSaved", function() {
                    t(function() {
                        n.currentMedicalRecord && (n.initPrint(), l())
                    })
                })
            })()
        }
    }
}]);
emrModule.factory("emrCustomizeDisplayUtil", ["$log", "$q", "$modal", "$compile", "$timeout", "enums", function(n, t, i, r, u, f) {
    "use strict";
    var o = function(n, t, i) {
            var f, o, h;
            !n || !n.rootFields || n.rootFields.length < 0 || (f = "", t.medicalLayoutFields = {}, t.fieldsHasEnableWhen = [], o = _(n.rootFields).sortBy(function(n) {
                return n.seqNum
            }), angular.forEach(o, function(n) {
                n.level = 0;
                var i = e(n, t);
                i && (f += i + "\n")
            }), h = r(f)(t), i.html(h), u(function() {
                s(i, t.fieldsHasEnableWhen)
            }))
        },
        s = function(n, t) {
            _.each(t, function(t) {
                var u = "div[field=\"medicalLayoutFields['" + t.fieldCode + "']\"]",
                    f = "div[field=\"medicalLayoutFields['" + t.enableWhenFieldCode + "']\"] > div.emr-field-content",
                    r = n.find(u).css("display", "inline-block").css("margin-left", "10px").css("vertical-align", "middle"),
                    i;
                if ((!t.optionData || !t.optionData.isKeepPositionWhenEdit) && (i = n.find(f), !$.contains(i, r) && !$.contains(r, i))) try {
                    r.appendTo(i)
                } catch (e) {
                    console.log(e)
                }
            })
        },
        e = function(n, t) {
            return (t.medicalLayoutFields[n.fieldCode] = n, n.enableWhenFieldCode && t.fieldsHasEnableWhen.push(n), n.inputType === f.FieldInputType.Group) ? h(n, t) : n.inputType === f.FieldInputType.RadioButton ? v(n, t) : n.inputType === f.FieldInputType.CheckBox ? y(n, t) : n.inputType === f.FieldInputType.InputText ? p(n, t) : n.inputType === f.FieldInputType.TextArea ? w(n, t) : n.inputType === f.FieldInputType.NumericUpDown ? a(n, t) : n.inputType === f.FieldInputType.PictureUploader ? c(n, t) : n.inputType === f.FieldInputType.NamedPictureUploader ? l(n, t) : n.inputType === f.FieldInputType.MedicalRecord_ChiefComplaint ? b(n, t) : n.inputType === f.FieldInputType.MedicalRecord_History ? k(n, t) : n.inputType === f.FieldInputType.MedicalRecord_PastHistory ? d(n, t) : n.inputType === f.FieldInputType.MedicalRecord_OralCheckRecord ? g(n, t) : n.inputType === f.FieldInputType.MedicalRecord_Imaging ? nt(n, t) : n.inputType === f.FieldInputType.MedicalRecord_RadiologyCheckRecord ? tt(n, t) : n.inputType === f.FieldInputType.MedicalRecord_DiagnoseRecord ? it(n, t) : n.inputType === f.FieldInputType.MedicalRecord_TreatmentAdvice ? rt(n, t) : n.inputType === f.FieldInputType.MedicalRecord_TreatmentPlan ? ut(n, t) : n.inputType === f.FieldInputType.MedicalRecord_CureRecord ? ft(n, t) : n.inputType === f.FieldInputType.MedicalRecord_Advice ? et(n, t) : n.inputType === f.FieldInputType.MedicalRecord_Comment ? ot(n, t) : void 0
        },
        st = function(n) {
            return n === f.FieldInputType.InputText || n === f.FieldInputType.TextArea || n === f.FieldInputType.RadioButton || n === f.FieldInputType.NumericUpDown || n === f.FieldInputType.PictureUploader || n === f.FieldInputType.NamedPictureUploader
        },
        h = function(n, t) {
            var i = [],
                r;
            return n.isShow = !1, n.subFields && n.subFields.length > 0 && (r = _.sortBy(n.subFields, function(n) {
                return n.seqNum
            }), angular.forEach(r, function(r) {
                r.level = n.level + 1;
                var u = e(r, t);
                r.isShow && (n.isShow = !0);
                u && i.push(u)
            })), n.isShow ? '<div class="emr-level-' + n.level + '" emr-field-name="' + n.fieldName + '">\n<div class="emr-level-' + n.level + '-group-title">\n<label>' + n.fieldName + '<\/label>\n<\/div>\n<div class="emr-level-' + n.level + '-group-content">\n' + i.join("\n") + "\n<\/div>\n<\/div>" : void 0
        },
        c = function(n, t) {
            return n.isShow = t.medicalRecord.customizeFields && t.medicalRecord.customizeFields[n.fieldCode] && t.medicalRecord.customizeFields[n.fieldCode].fieldValue, n.isShow ? "<emr-free-picture-display-view\ncurrent-value=\"medicalRecord.customizeFields['" + n.fieldCode + "']\"\nfield=\"medicalLayoutFields['" + n.fieldCode + "']\">\n<\/emr-free-picture-display-view>" : ""
        },
        l = function(n, t) {
            return n.isShow = t.medicalRecord.customizeFields && t.medicalRecord.customizeFields[n.fieldCode] && t.medicalRecord.customizeFields[n.fieldCode].fieldValue, n.isShow ? "<emr-free-named-picture-display-view\ncurrent-value=\"medicalRecord.customizeFields['" + n.fieldCode + "']\"\nfield=\"medicalLayoutFields['" + n.fieldCode + "']\">\n<\/emr-free-named-picture-display-view>" : ""
        },
        a = function(n, t) {
            return n.isShow = t.medicalRecord.customizeFields && t.medicalRecord.customizeFields[n.fieldCode] && (t.medicalRecord.customizeFields[n.fieldCode].fieldValue || t.medicalRecord.customizeFields[n.fieldCode].fieldValue == 0), n.isShow ? "<emr-free-number-display-view\ncurrent-value=\"medicalRecord.customizeFields['" + n.fieldCode + "']\"\nfield=\"medicalLayoutFields['" + n.fieldCode + "']\">\n<\/emr-free-number-display-view>" : ""
        },
        v = function(n, t) {
            return n.isShow = t.medicalRecord.customizeFields && t.medicalRecord.customizeFields[n.fieldCode] && t.medicalRecord.customizeFields[n.fieldCode].fieldValue, n.isShow ? "<emr-free-radio-display-view\ncurrent-value=\"medicalRecord.customizeFields['" + n.fieldCode + "']\"\nfield=\"medicalLayoutFields['" + n.fieldCode + "']\">\n<\/emr-free-radio-display-view>" : ""
        },
        y = function(n, t) {
            return n.isShow = t.medicalRecord.customizeFields && t.medicalRecord.customizeFields[n.fieldCode] && t.medicalRecord.customizeFields[n.fieldCode].fieldValue, n.isShow ? "<emr-free-checkbox-display-view\ncurrent-value=\"medicalRecord.customizeFields['" + n.fieldCode + "']\"\nfield=\"medicalLayoutFields['" + n.fieldCode + "']\">\n<\/emr-free-checkbox-display-view>" : ""
        },
        p = function(n, t) {
            return n.isShow = t.medicalRecord.customizeFields && t.medicalRecord.customizeFields[n.fieldCode] && t.medicalRecord.customizeFields[n.fieldCode].fieldValue, n.isShow ? "<emr-free-input-display-view\n current-value=\"medicalRecord.customizeFields['" + n.fieldCode + "']\"\nfield=\"medicalLayoutFields['" + n.fieldCode + "']\">\n<\/emr-free-input-display-view>" : ""
        },
        w = function(n, t) {
            return n.isShow = t.medicalRecord.customizeFields && t.medicalRecord.customizeFields[n.fieldCode] && t.medicalRecord.customizeFields[n.fieldCode].fieldValue, n.isShow ? "<emr-free-textarea-display-view\n current-value=\"medicalRecord.customizeFields['" + n.fieldCode + "']\"\nfield=\"medicalLayoutFields['" + n.fieldCode + "']\">\n<\/emr-free-textarea-display-view>" : ""
        },
        b = function(n, t) {
            return n.isShow = t.medicalRecord.chiefComplaint, n.isShow ? '<emr-chief-complaint-display-view\ntitle="medicalRecord.name"\nfield="medicalLayoutFields[\'' + n.fieldCode + '\']"\ncurrent-value="medicalRecord.chiefComplaint"><\/emr-chief-complaint-display-view>' : ""
        },
        k = function(n, t) {
            return n.isShow = t.medicalRecord.history, n.isShow ? "<emr-history-display-view\nfield=\"medicalLayoutFields['" + n.fieldCode + '\']"\ncurrent-value="medicalRecord.history"><\/emr-history-display-view>' : ""
        },
        d = function(n, t) {
            return n.isShow = t.medicalRecord.pastHistory, n.isShow ? "<emr-past-history-display-view\nfield=\"medicalLayoutFields['" + n.fieldCode + '\']"\ncurrent-value="medicalRecord.pastHistory"><\/emr-past-history-display-view>' : ""
        },
        g = function(n, t) {
            return n.isShow = t.medicalRecord.oralCheckRecordList && t.medicalRecord.oralCheckRecordList.length > 0, n.isShow ? '<emr-oral-check-records-display-view\nis-emr-custom-template-enabled="isEmrCustomTemplateEnabled"\nallow-edit-tooth="allowEditTooth"\nallow-tooth-fdi="allowToothFdi"\nfield="medicalLayoutFields[\'' + n.fieldCode + '\']"\ncurrent-value="medicalRecord.oralCheckRecordList"><\/emr-oral-check-records-display-view>' : ""
        },
        nt = function(n, t) {
            return n.isShow = t.medicalRecord.associatedImageList && t.medicalRecord.associatedImageList.length > 0, n.isShow ? "<emr-medical-image-display-view\nfield=\"medicalLayoutFields['" + n.fieldCode + '\']"\ncurrent-value="medicalRecord.associatedImageList"><\/emr-medical-image-display-view>' : ""
        },
        tt = function(n, t) {
            return n.isShow = t.medicalRecord.radiologyCheckRecordList && t.medicalRecord.radiologyCheckRecordList.length > 0, n.isShow ? '<emr-radiology-check-records-display-view\nis-emr-custom-template-enabled="isEmrCustomTemplateEnabled"\nallow-edit-tooth="allowEditTooth"\nallow-tooth-fdi="allowToothFdi"\nfield="medicalLayoutFields[\'' + n.fieldCode + '\']"\ncurrent-value="medicalRecord.radiologyCheckRecordList"><\/emr-radiology-check-records-display-view>' : ""
        },
        it = function(n, t) {
            return n.isShow = t.medicalRecord.diagnoseRecordList && t.medicalRecord.diagnoseRecordList.length > 0, n.isShow ? '<emr-diagnose-records-display-view\nis-emr-custom-template-enabled="isEmrCustomTemplateEnabled"\nallow-edit-tooth="allowEditTooth"\nallow-tooth-fdi="allowToothFdi"\nfield="medicalLayoutFields[\'' + n.fieldCode + '\']"\ncurrent-value="medicalRecord.diagnoseRecordList"><\/emr-diagnose-records-display-view>' : ""
        },
        rt = function(n, t) {
            return n.isShow = t.medicalRecord.treatmentAdviceList && t.medicalRecord.treatmentAdviceList.length > 0, n.isShow ? '<emr-treatment-advices-display-view\nallow-edit-tooth="allowEditTooth"\nallow-tooth-fdi="allowToothFdi"\nfield="medicalLayoutFields[\'' + n.fieldCode + '\']"\ncurrent-value="medicalRecord.treatmentAdviceList"><\/emr-treatment-advices-display-view>' : ""
        },
        ut = function(n, t) {
            return n.isShow = t.medicalRecord.treatmentPlanList && t.medicalRecord.treatmentPlanList.length > 0, n.isShow ? '<emr-treatment-plans-display-view\nis-emr-custom-template-enabled="isEmrCustomTemplateEnabled"\nallow-edit-tooth="allowEditTooth"\nallow-tooth-fdi="allowToothFdi"\nfield="medicalLayoutFields[\'' + n.fieldCode + '\']"\ncurrent-value="medicalRecord.treatmentPlanList"><\/emr-treatment-plans-display-view>' : ""
        },
        ft = function(n, t) {
            return n.isShow = t.medicalRecord.cureRecordList && t.medicalRecord.cureRecordList.length > 0, n.isShow ? '<emr-cure-records-display-view\nis-emr-custom-template-enabled="isEmrCustomTemplateEnabled"\nallow-edit-tooth="allowEditTooth"\nallow-tooth-fdi="allowToothFdi"\nfield="medicalLayoutFields[\'' + n.fieldCode + '\']"\ncurrent-value="medicalRecord.cureRecordList"><\/emr-cure-records-display-view>' : ""
        },
        et = function(n, t) {
            return n.isShow = t.medicalRecord.advice, n.isShow ? "<emr-advice-display-view\nfield=\"medicalLayoutFields['" + n.fieldCode + '\']"\ncurrent-value="medicalRecord.advice"><\/emr-advice-display-view>' : ""
        },
        ot = function(n, t) {
            return n.isShow = t.medicalRecord.comment, n.isShow ? "<emr-comment-display-view\nfield=\"medicalLayoutFields['" + n.fieldCode + '\']"\ncurrent-value="medicalRecord.comment"><\/emr-comment-display-view>' : ""
        };
    return {
        buildDisplayEmrHtml: o
    }
}]);
emrModule.factory("emrCustomizeEditUtil", ["$log", "$q", "$modal", "$compile", "$timeout", "enums", function(n, t, i, r, u, f) {
    "use strict";
    var s = function(n, t, i) {
            var f, e, s;
            !n || !n.rootFields || n.rootFields.length < 0 || (i.empty(), f = "", t.currentMedicalLayoutFields = {}, t.fieldsHasEnableWhen = [], t.currentMedicalRecord.customizeFields || (t.currentMedicalRecord.customizeFields = {}), c(t), e = _(n.rootFields).sortBy(function(n) {
                return n.seqNum
            }), angular.forEach(e, function(n) {
                n.level = 0;
                var i = o(n, t);
                i && (f += i + "\n")
            }), s = r(f)(t), i.html(s), u(function() {
                h(i, t.fieldsHasEnableWhen)
            }))
        },
        h = function(n, t) {
            _.each(t, function(t) {
                var u = "div[field=\"currentMedicalLayoutFields['" + t.fieldCode + "']\"]",
                    f = "div[field=\"currentMedicalLayoutFields['" + t.enableWhenFieldCode + "']\"] > div.emr-field-content",
                    r = n.find(u).css({
                        display: ""
                    }),
                    i;
                if ((!t.optionData || !t.optionData.isKeepPositionWhenEdit) && (i = n.find(f), !$.contains(i, r) && !$.contains(r, i))) try {
                    i.find("div.checkbox-group").length ? e(i.find("div.checkbox-group"), r) : i.find("div.radio-group").length ? e(i.find("div.radio-group"), r) : r.addClass("emr-enable-when").appendTo(i)
                } catch (o) {
                    console.log(o)
                }
            })
        },
        e = function(n, t) {
            var r = t.attr("emr-enable-field-value"),
                i;
            n.length !== 0 && (i = n.find("input[value=" + r + "]"), i.length && (t.find("textarea").css("margin", "0"), i.parent().append(t)))
        },
        c = function(n) {
            n.hasChiefComplaint = !1;
            n.hasHistory = !1;
            n.hasPastHistory = !1;
            n.hasOralCheckRecord = !1;
            n.hasRadiologyCheckRecord = !1;
            n.hasDiagnoseRecord = !1;
            n.hasTreatmentAdvice = !1;
            n.hasTreatmentPlan = !1;
            n.hasCureRecord = !1;
            n.hasAdvice = !1;
            n.hasArchive = !1;
            n.hasComment = !1;
            n.hasAssociatedImage = !1
        },
        o = function(n, t) {
            return (l(n.inputType) && (t.currentMedicalRecord.customizeFields[n.fieldCode] ? t.currentMedicalRecord.customizeFields[n.fieldCode].inputType = n.inputType : t.currentMedicalRecord.customizeFields[n.fieldCode] = {
                id: 0,
                mid: t.currentMedicalRecord.id,
                fieldCode: n.fieldCode,
                fieldValue: "",
                inputType: n.inputType
            }), t.currentMedicalLayoutFields[n.fieldCode] = n, n.enableWhenFieldCode && (t.fieldsHasEnableWhen.push(n), n.getEnableWhenField = function() {
                return _.find(t.currentMedicalRecord.customizeFields, function(t) {
                    return t.fieldCode === n.enableWhenFieldCode
                })
            }), n.inputType === f.FieldInputType.Group) ? a(n, t) : n.inputType === f.FieldInputType.RadioButton ? w(n, t) : n.inputType === f.FieldInputType.CheckBox ? b(n, t) : n.inputType === f.FieldInputType.InputText ? k(n, t) : n.inputType === f.FieldInputType.TextArea ? d(n, t) : n.inputType === f.FieldInputType.NumericUpDown ? p(n, t) : n.inputType === f.FieldInputType.PictureUploader ? v(n, t) : n.inputType === f.FieldInputType.NamedPictureUploader ? y(n, t) : n.inputType === f.FieldInputType.MedicalRecord_ChiefComplaint ? (t.hasChiefComplaint = !0, g(n, t)) : n.inputType === f.FieldInputType.MedicalRecord_History ? (t.hasHistory = !0, nt(n, t)) : n.inputType === f.FieldInputType.MedicalRecord_PastHistory ? (t.hasPastHistory = !0, tt(n, t)) : n.inputType === f.FieldInputType.MedicalRecord_OralCheckRecord ? (t.hasOralCheckRecord = !0, it(n, t)) : n.inputType === f.FieldInputType.MedicalRecord_Imaging ? (t.hasAssociatedImage = !0, rt(n, t)) : n.inputType === f.FieldInputType.MedicalRecord_RadiologyCheckRecord ? (t.hasRadiologyCheckRecord = !0, ut(n, t)) : n.inputType === f.FieldInputType.MedicalRecord_DiagnoseRecord ? (t.hasDiagnoseRecord = !0, ft(n, t)) : n.inputType === f.FieldInputType.MedicalRecord_TreatmentAdvice ? (t.hasTreatmentAdvice = !0, et(n, t)) : n.inputType === f.FieldInputType.MedicalRecord_TreatmentPlan ? (t.hasTreatmentPlan = !0, ot(n, t)) : n.inputType === f.FieldInputType.MedicalRecord_CureRecord ? (t.hasCureRecord = !0, st(n, t)) : n.inputType === f.FieldInputType.MedicalRecord_Advice ? (t.hasAdvice = !0, ht(n, t)) : n.inputType === f.FieldInputType.MedicalRecord_Archive ? (t.hasArchive = !0, ct(n, t)) : n.inputType === f.FieldInputType.MedicalRecord_Comment ? (t.hasComment = !0, lt(n, t)) : void 0
        },
        l = function(n) {
            return n === f.FieldInputType.InputText || n === f.FieldInputType.TextArea || n === f.FieldInputType.RadioButton || n === f.FieldInputType.CheckBox || n === f.FieldInputType.NumericUpDown || n === f.FieldInputType.PictureUploader || n === f.FieldInputType.NamedPictureUploader
        },
        a = function(n, t) {
            var i = [],
                r;
            return n.subFields && n.subFields.length > 0 && (r = _.sortBy(n.subFields, function(n) {
                return n.seqNum
            }), angular.forEach(r, function(r) {
                r.level = n.level + 1;
                var u = o(r, t);
                u && i.push(u)
            })), '<div class="emr-level-' + n.level + '" emr-field-name="' + n.fieldName + '">\n<div class="emr-level-' + n.level + '-group-title">\n<label>' + n.fieldName + '<\/label>\n<\/div>\n<div class="emr-level-' + n.level + '-group-content">\n' + i.join("\n") + "\n<\/div>\n<\/div>"
        },
        v = function(n) {
            return "<emr-free-picture-edit-view current-value=\"currentMedicalRecord.customizeFields['" + n.fieldCode + "']\"\nfield=\"currentMedicalLayoutFields['" + n.fieldCode + "']\"\n" + (n.enableWhenFieldCode ? 'style="display: none">\n' : ">\n") + "<\/emr-free-picture-edit-view>"
        },
        y = function(n) {
            return "<emr-free-named-picture-edit-view current-value=\"currentMedicalRecord.customizeFields['" + n.fieldCode + "']\"\nfield=\"currentMedicalLayoutFields['" + n.fieldCode + "']\"\n" + (n.enableWhenFieldCode ? 'style="display: none">\n' : ">\n") + "<\/emr-free-named-picture-edit-view>"
        },
        p = function(n) {
            return "<emr-free-number-edit-view current-value=\"currentMedicalRecord.customizeFields['" + n.fieldCode + "']\"\nfield=\"currentMedicalLayoutFields['" + n.fieldCode + "']\"\n" + (n.enableWhenFieldCode ? 'style="display: none">\n' : ">\n") + "<\/emr-free-number-edit-view>"
        },
        w = function(n) {
            return "<emr-free-radio-edit-view current-value=\"currentMedicalRecord.customizeFields['" + n.fieldCode + "']\"\nfield=\"currentMedicalLayoutFields['" + n.fieldCode + "']\"\n" + (n.enableWhenFieldCode ? 'style="display: none">\n' : ">\n") + "<\/emr-free-radio-edit-view>"
        },
        b = function(n) {
            return "<emr-free-checkbox-edit-view current-value=\"currentMedicalRecord.customizeFields['" + n.fieldCode + "']\"\nfield=\"currentMedicalLayoutFields['" + n.fieldCode + "']\"\n" + (n.enableWhenFieldCode ? 'style="display: none">\n' : ">\n") + "<\/emr-free-checkbox-edit-view>"
        },
        k = function(n) {
            return "<emr-free-input-edit-view current-value=\"currentMedicalRecord.customizeFields['" + n.fieldCode + "']\"\nfield=\"currentMedicalLayoutFields['" + n.fieldCode + "']\"\n" + (n.enableWhenFieldCode ? 'style="display: none">\n' : ">\n") + "<\/emr-free-input-edit-view>"
        },
        d = function(n) {
            return "<emr-free-textarea-edit-view current-value=\"currentMedicalRecord.customizeFields['" + n.fieldCode + "']\"\nfield=\"currentMedicalLayoutFields['" + n.fieldCode + "']\"\n" + (n.enableWhenFieldCode ? 'style="display: none">\n' : ">\n") + "<\/emr-free-textarea-edit-view>"
        },
        g = function(n) {
            return '<emr-chief-complaint-edit-view ng-if="currentMedicalRecord.isShowChiefComplaint"\nis-first-visit="currentMedicalRecord.firstVisit"\nlevel="topLevelNode"\nfield="currentMedicalLayoutFields[\'' + n.fieldCode + '\']"\ncurrent-value="currentMedicalRecord.chiefComplaint"\n' + (n.enableWhenFieldCode ? 'style="display: none"\n' : "") + 'on-focus="setEMRControlFocus"><\/emr-chief-complaint-edit-view>'
        },
        nt = function(n) {
            return '<emr-history-edit-view ng-if="currentMedicalRecord.isShowHistory"\nlevel="topLevelNode"\nfield="currentMedicalLayoutFields[\'' + n.fieldCode + '\']"\ncurrent-value="currentMedicalRecord.history"\n' + (n.enableWhenFieldCode ? 'style="display: none"\n' : "") + 'on-focus="setEMRControlFocus"><\/emr-history-edit-view>'
        },
        tt = function(n) {
            return '<emr-past-history-edit-view ng-if="currentMedicalRecord.isShowPastHistory"\nlevel="topLevelNode"\nfield="currentMedicalLayoutFields[\'' + n.fieldCode + '\']"\ncurrent-value="currentMedicalRecord.pastHistory"\n' + (n.enableWhenFieldCode ? 'style="display: none"\n' : "") + 'on-focus="setEMRControlFocus"><\/emr-past-history-edit-view>'
        },
        it = function(n) {
            return '<emr-oral-check-records-edit-view ng-if="currentMedicalRecord.isShowOralCheckRecordList"\nis-emr-custom-template-enabled="isEmrCustomTemplateEnabled"\nlevel="topLevelNode"\nallow-edit-tooth="allowEditToothFDI"\nfield="currentMedicalLayoutFields[\'' + n.fieldCode + '\']"\non-record-tooth="onRecordTooth"\non-exam-importing="importTooth"\non-exam-imported="removeEmptyRecord"\ncurrent-value="currentMedicalRecord.oralCheckRecordList"\npatient-id="currentMedicalRecord.patientId"\nopen-tag="true"\n' + (n.enableWhenFieldCode ? 'style="display: none"\n' : "") + 'on-focus="setEMRControlFocus"\non-sync-tooth-code="onSyncToothCode"\non-delete-tooth-code="onDeleteToothCode"><\/emr-oral-check-records-edit-view>'
        },
        rt = function(n) {
            return '<emr-medical-image-edit-view ng-if="currentMedicalRecord.isShowAssociatedImage"current-value="currentMedicalRecord.associatedImageList"\nfield="currentMedicalLayoutFields[\'' + n.fieldCode + '\']"\npatient-id="currentMedicalRecord.patientId"\n' + (n.enableWhenFieldCode ? 'style="display: none">\n' : ">\n") + "<\/emr-medical-image-edit-view>"
        },
        ut = function(n) {
            return '<emr-radiology-check-records-edit-view ng-if="currentMedicalRecord.isShowRadiologyCheckRecordList"\nis-emr-custom-template-enabled="isEmrCustomTemplateEnabled"\nlevel="topLevelNode"\nallow-edit-tooth="allowEditToothFDI"\non-record-tooth="onRecordTooth"\nfield="currentMedicalLayoutFields[\'' + n.fieldCode + '\']"\ncurrent-value="currentMedicalRecord.radiologyCheckRecordList"\n' + (n.enableWhenFieldCode ? 'style="display: none"\n' : "") + 'on-focus="setEMRControlFocus"\non-sync-tooth-code="onSyncToothCode"\non-delete-tooth-code="onDeleteToothCode"><\/emr-radiology-check-records-edit-view>'
        },
        ft = function(n) {
            return '<emr-diagnose-records-edit-view ng-if="currentMedicalRecord.isShowDiagnoseRecordList"\nis-emr-custom-template-enabled="isEmrCustomTemplateEnabled"\nlevel="topLevelNode"\non-record-tooth="onRecordTooth"\nallow-edit-tooth="allowEditToothFDI"\nfield="currentMedicalLayoutFields[\'' + n.fieldCode + '\']"\ncurrent-value="currentMedicalRecord.diagnoseRecordList"\n' + (n.enableWhenFieldCode ? 'style="display: none"\n' : "") + 'on-focus="setEMRControlFocus"\non-sync-tooth-code="onSyncToothCode"\non-delete-tooth-code="onDeleteToothCode"><\/emr-diagnose-records-edit-view>'
        },
        et = function(n) {
            return '<emr-treatment-advices-edit-view ng-if="currentMedicalRecord.isShowTreatmentAdviceList"\nlevel="topLevelNode"\non-record-tooth="onRecordTooth"\nallow-edit-tooth="allowEditToothFDI"\nfield="currentMedicalLayoutFields[\'' + n.fieldCode + '\']"\ncurrent-value="currentMedicalRecord.treatmentAdviceList"\n' + (n.enableWhenFieldCode ? 'style="display: none"\n' : "") + 'on-focus="setEMRControlFocus"\non-sync-tooth-code="onSyncToothCode"\non-delete-tooth-code="onDeleteToothCode"><\/emr-treatment-advices-edit-view>'
        },
        ot = function(n) {
            return '<emr-treatment-plans-edit-view ng-if="currentMedicalRecord.isShowTreatmentPlanList"\nis-emr-custom-template-enabled="isEmrCustomTemplateEnabled"\nlevel="topLevelNode"\non-record-tooth="onRecordTooth"\nallow-edit-tooth="allowEditToothFDI"\nfield="currentMedicalLayoutFields[\'' + n.fieldCode + '\']"\ncurrent-value="currentMedicalRecord.treatmentPlanList"\npatient-id="currentMedicalRecord.patientId"\n' + (n.enableWhenFieldCode ? 'style="display: none"\n' : "") + 'on-focus="setEMRControlFocus"\non-sync-tooth-code="onSyncToothCode"\non-delete-tooth-code="onDeleteToothCode"><\/emr-treatment-plans-edit-view>'
        },
        st = function(n) {
            return '<emr-cure-records-edit-view ng-if="currentMedicalRecord.isShowCureRecordList"\nis-emr-custom-template-enabled="isEmrCustomTemplateEnabled"\nlevel="topLevelNode"\non-record-tooth="onRecordTooth"\nallow-edit-tooth="allowEditToothFDI"\nfield="currentMedicalLayoutFields[\'' + n.fieldCode + '\']"\ncurrent-value="currentMedicalRecord.cureRecordList"\nappt-id="currentMedicalRecord.appointId"\n' + (n.enableWhenFieldCode ? 'style="display: none"\n' : "") + 'on-focus="setEMRControlFocus"\non-sync-tooth-code="onSyncToothCode"\non-delete-tooth-code="onDeleteToothCode"><\/emr-cure-records-edit-view>'
        },
        ht = function(n) {
            return '<emr-advice-edit-view ng-if="currentMedicalRecord.isShowAdvice"\nlevel="topLevelNode"\nfield="currentMedicalLayoutFields[\'' + n.fieldCode + '\']"\ncurrent-value="currentMedicalRecord.advice"\n' + (n.enableWhenFieldCode ? 'style="display: none"\n' : "") + 'on-focus="setEMRControlFocus"><\/emr-advice-edit-view>'
        },
        ct = function(n) {
            return '<emr-archive-edit-view\nlevel="topLevelNode"\nfield="currentMedicalLayoutFields[\'' + n.fieldCode + '\']"\ncurrent-value="currentMedicalRecord.archive"\n' + (n.enableWhenFieldCode ? 'style="display: none"\n' : "") + 'on-focus="setEMRControlFocus"><\/emr-archive-edit-view>'
        },
        lt = function(n) {
            return '<emr-comment-edit-view\nlevel="topLevelNode"\nfield="currentMedicalLayoutFields[\'' + n.fieldCode + '\']"\ncurrent-value="currentMedicalRecord.comment"\n' + (n.enableWhenFieldCode ? 'style="display: none"\n' : "") + 'on-focus="setEMRControlFocus"><\/emr-comment-edit-view>'
        },
        at = function(n, t) {
            return function() {
                var r, i = n.getEnableWhenField(),
                    u;
                return i && n.enableWhenOperator === f.CondOperator.Equal || (r = !1), i && (i.inputType === f.FieldInputType.CheckBox ? i.fieldValue && (u = i.fieldValue.split("|"), r = _.contains(u, n.enableWhenFieldValue)) : r = i.fieldValue === n.enableWhenFieldValue), r || (t.fieldValue = n.defaultValue), r
            }
        },
        vt = function() {
            return ["chiefComplaintHistory", "oralCheck", "diagnoseTreatmentPlan", "cureAdvice", "other"]
        };
    return {
        buildEditEmrHtml: s,
        getEnableWhen: at,
        getEmrCategories: vt
    }
}]);
emrModule.directive("emrCustomTemplateView", ["$log", "$timeout", "$modal", "appointmentSvc", "patientDocumentSvc", "loginContext", "schedulerUtil", "practiceSvc", "constants", "patientSvc", "dataDicSvc", "aresNotification", function(n, t, i, r, u, f, e, o, s, h, c, l) {
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/emr/views/emr-custom-template-view.html",
        link: function(n, h) {
            var v = null,
                d = function() {
                    o.getDoctors().success(function(t) {
                        var u, r, i;
                        n.doctors = t;
                        u = null;
                        r = h.find("#doctor").kendoNameCodeFilterComboBox({
                            dataSource: n.doctors,
                            filter: "contains",
                            placeholder: "请选择医生",
                            dataTextField: "name",
                            dataValueField: "id",
                            select: function(t) {
                                var i = this.dataItem(t.item.index());
                                n.currentDoctor = i
                            }
                        }).data("kendoNameCodeFilterComboBox");
                        f.isDoctor && (i = _.findIndex(n.doctors, function(n) {
                            return n.id == f.providerId
                        }), r.select(i), n.currentDoctor = n.doctors[i])
                    })
                },
                g = function() {
                    var t = [];
                    c.nurseDic.loadActive().then(function(i) {
                        angular.forEach(i, function(n) {
                            t.push(n)
                        });
                        c.assistantDic.loadActive().then(function(i) {
                            angular.forEach(i, function(n) {
                                t.push(n)
                            });
                            n.nurses = t;
                            h.find("#nurse").kendoNameCodeFilterComboBox({
                                dataSource: n.nurses,
                                filter: "contains",
                                placeholder: "请选择护士",
                                dataTextField: "name",
                                dataValueField: "id",
                                select: function(t) {
                                    var i = this.dataItem(t.item.index());
                                    n.currentAssistant = i
                                }
                            })
                        })
                    })
                },
                nt = function() {
                    var t = {
                        officeId: f.officeId,
                        patientId: n.patientId,
                        endTime: moment(Ares.today()).add(1, "d").format(s.dateFormat),
                        isCancelled: !1,
                        isPending: !1,
                        isFailed: !1
                    };
                    a(!1);
                    r.searchAppointments(t).success(function(t) {
                        var f, i, r;
                        if (t.length > 0) {
                            for (n.isFirstVisit = !1, f = angular.copy(t), i = 0; i < t.length; ++i) t[i].startTimeStr = moment(t[i].startTime).format("YYYY年MM月DD日 HH:mm");
                            $;
                            n.historyAppts = t;
                            n.document.appointmentId = t[0].id;
                            n.defualtStartTime = moment(t[0].startTime).format(s.dateFormat);
                            p();
                            var e = moment(Ares.today()).format(s.dateFormat),
                                o = moment(Ares.today()).add(1, "d").format(s.dateFormat),
                                u = _.filter(f, function(n) {
                                    return n.startTime >= e && n.startTime < o
                                });
                            u && u.length > 1 && w(u)
                        } else r = b(), a(!0), r.isFirstVisit = !0, n.isFirstVisit = !0, r.startTimeStr = moment(r.startTime).format("YYYY年MM月DD日 HH:mm"), n.historyAppts = [r], p()
                    })
                },
                tt = function(t) {
                    t && (n.document && n.document.templateId == t.id ? (n.document.templateId = null, n.errorMsg = "请选择模板") : (n.document.templateId = t.id, n.document.template = t, n.errorMsg = null))
                },
                it = function() {
                    if (!n.document.templateId > 0 && (n.errorMsg = "请选择模板"), !n.currentDoctor) {
                        l.error("请选择医生");
                        return
                    }
                    n.errorMsg == null && (n.document.template.documentTemplateFields && n.document.template.documentTemplateFields.length != 0 || u.getDocTemplateList({
                        isWithFields: !0,
                        templateId: n.document.templateId
                    }).success(function(t) {
                        if (t && t.length > 0) n.document.template = t[0], rt(), n.save();
                        else {
                            n.errorMsg = "请选择正确模板";
                            return
                        }
                    }))
                },
                rt = function() {
                    var f = _.find(n.document.template.documentTemplateFields, {
                            fieldCode: "Doctor"
                        }),
                        t, i, r, u;
                    f && n.currentDoctor && (f.fieldValue = n.currentDoctor.name);
                    t = _.find(n.document.template.documentTemplateFields, {
                        fieldCode: "Assistant"
                    });
                    t && n.currentAssistant && (t.fieldValue = n.currentAssistant.name);
                    i = _.find(n.document.template.documentTemplateFields, {
                        fieldCode: "AppointDate"
                    });
                    r = _.find(n.historyAppts, {
                        id: n.document.appointmentId || -2
                    });
                    r && i && (i.fieldValue = r.startTime);
                    u = _.find(n.document.template.documentTemplateFields, {
                        fieldCode: "EmrType"
                    });
                    u && (u.fieldValue = n.isEmrFirstVisit ? "初诊" : "复诊")
                },
                p = function() {
                    h.find("#appoint").kendoDropDownList({
                        dataSource: n.historyAppts,
                        placeholder: "请选择",
                        valueTemplate: '<span class="k-state-default">#: data.startTimeStr #<\/span>',
                        template: '<span class="k-state-default">#: data.startTimeStr #<\/span>',
                        dataValueField: "id",
                        select: function(t) {
                            var i = this.dataItem(t.item.index());
                            i && (n.document.appointmentId = i.id, a(i.id > 0 ? !1 : !0), n.$apply())
                        }
                    })
                },
                y = function(t) {
                    var i = $("#appoint").data("kendoDropDownList");
                    i && (i.value(t), n.document.appointmentId = t)
                },
                ut = function() {
                    var i = h.find("#appoint").data("kendoDropDownList"),
                        t = {
                            officeId: f.officeId,
                            patientId: n.patientId,
                            startTime: moment(n.defualtStartTime).format(s.dateFormat),
                            endTime: moment(n.defualtStartTime).add(1, "d").format(s.dateFormat),
                            isCancelled: !1,
                            isFailed: !1,
                            isPending: !1
                        };
                    a(!1);
                    r.searchAppointmentsByTenant(t).success(function(t) {
                        var f, i, r, u;
                        t.length == 1 ? y(t[0].id) : t.length > 1 ? (f = angular.copy(t), w(f)) : (i = b(), i.isFirstVisit = n.isFirstVisit, i.startTimeStr = moment(i.startTime).format("YYYY年MM月DD日 HH:mm"), r = _.findIndex(n.historyAppts, {
                            id: -2
                        }), r > -1 ? n.historyAppts.splice(r, 1, i) : n.historyAppts.push(i), u = h.find("#appoint").data("kendoDropDownList"), u != null && (u.dataSource.data(n.historyAppts), y(-2)), a(!0))
                    })
                },
                w = function(t) {
                    var r = i.open({
                        animation: !0,
                        backdrop: "static",
                        template: "<appt-list-dialog><\/appt-list-dialog>",
                        controller: "apptListDialogCtrl",
                        size: "md",
                        resolve: {
                            host: function() {
                                return {
                                    apptList: t,
                                    patientId: n.patientId
                                }
                            }
                        }
                    });
                    r.result.then(function(t) {
                        t && (y(t.id), n.defualtStartTime = moment(t.startTime).format(s.dateFormat))
                    })
                },
                b = function() {
                    var t = ft();
                    return {
                        id: -2,
                        startTime: t.startDate,
                        endTime: t.endDate,
                        patientId: n.patientId,
                        isFirstVisit: !0,
                        appointmentType: 1,
                        isCheckedIn: !0,
                        notes: "由病历创建的预约"
                    }
                },
                ft = function() {
                    var r = new Date,
                        t, i, u, f;
                    return n.defualtStartTime = n.defualtStartTime || r, n.defualtStartTime.setHours(r.getHours()), n.defualtStartTime.setMinutes(r.getMinutes()), t = moment(n.defualtStartTime), i = moment().format("mm") * 1, i < 15 ? t.minutes(15) : i > 15 && i < 30 ? t.minutes(30) : i > 30 && i < 45 ? t.minutes(45) : i > 45 && (t.minutes(0), t.add(1, "hour")), u = moment(t).format("YYYY-MM-DD HH:mm"), f = moment(u).add(30, "m").format("YYYY-MM-DD HH:mm"), {
                        startDate: u,
                        endDate: f
                    }
                },
                et = function() {
                    var i = k(),
                        r = moment(i.value()).format("HH:mm"),
                        u = moment(i.value()).add(30, "m").format("HH:mm"),
                        t = _.find(n.historyAppts, {
                            id: -2
                        }),
                        f;
                    t && (t.startTime = moment(t.startTime).format("YYYY-MM-DD " + r), t.startTimeStr = moment(t.startTime).format("YYYY年MM月DD日 " + r), t.endTime = moment(t.endTime).format("YYYY-MM-DD " + u), t.endTimeStr = moment(t.endTime).format("YYYY年MM月DD日 " + u), f = h.find("#appoint").data("kendoDropDownList"), f.dataSource.data(n.historyAppts))
                },
                a = function(n) {
                    var t = k();
                    t && t.enable(n)
                },
                k = function() {
                    return v || (v = h.find("#apptTimePicker").data("kendoTimePicker")), v
                },
                ot = function() {
                    e.loadSchedulerConfig().then(function(t) {
                        n.timePickerOption = t && t.timeSlotUnit ? {
                            interval: t.timeSlotUnit
                        } : {
                            interval: 30
                        }
                    })
                },
                st = function() {
                    d();
                    g();
                    ot();
                    t(function() {
                        nt()
                    }, 150)
                };
            (function() {
                n.today = new Date;
                n.defualtStartTime = new Date;
                n.document = {
                    name: "患者病历文档",
                    categoryId: 2
                };
                n.saveValidate = it;
                n.selectedTemplate = tt;
                n.onApptTimeChanged = ut;
                n.onTimePickerChanged = et;
                n.isEmrFirstVisit = !0;
                st();
                t(function() {
                    Ares.centerModal(h.closest(".modal-dialog"))
                }, 100)
            })()
        }
    }
}]);
emrModule.directive("emrWorkflowView", ["$log", "$q", "$timeout", "$modal", "dataDicSvc", "eventAggregator", function(n, t, i) {
    return {
        replace: !0,
        templateUrl: "/app/emr/views/emr-workflow-view.html",
        link: function(n, t) {
            (function() {
                i(function() {
                    Ares.centerModal(t.closest(".modal-dialog"))
                }, 100)
            })()
        }
    }
}]);
emrModule.directive("patientEmrHomeView", ["$log", "$timeout", "$state", "$stateParams", function() {
    "use strict";
    return {
        restrict: "E",
        templateUrl: "/app/emr/views/patient-emr-home-view.html",
        link: function() {}
    }
}]);
emrModule.directive("patientNewEmrEditTemplateChoiceView", ["$modal", "loginContext", "localCache", function(n, t, i) {
    "use strict";
    return {
        replace: !0,
        templateUrl: "/app/emr/views/patient-new-emr-edit-template-choice-view.html",
        link: function(r) {
            var f = i.getCache(i.keys.EmrTemplateExemptionAgreementCheck),
                u = f.loadObject(),
                o = function() {
                    r.closeTemplateData()
                },
                s = function() {
                    r.saveTemplateData()
                },
                h = function(n) {
                    if (r.currentEmrTemplate = angular.copy(n), r.showExemptionAgreement = !0, r.agreeExemptionAgreement = !1, _.isArray(u)) {
                        var i = u.find(n => n.userId == t.userId);
                        i && i.checked && (r.agreeExemptionAgreement = !0)
                    }
                    event.stopPropagation()
                },
                c = function() {
                    n.open({
                        animation: !0,
                        backdrop: "static",
                        template: "<patient-new-emr-exemption-agreement-view><\/patient-new-emr-exemption-agreement-view>",
                        controller: "PatientNewEmrExemptionAgreementCtrl",
                        size: "sm"
                    }).result.then(function() {
                        r.agreeExemptionAgreement = !1;
                        e()
                    })
                },
                e = function() {
                    r.agreeExemptionAgreement = !r.agreeExemptionAgreement;
                    _.isArray(u) || (u = []);
                    var n = u.find(n => n.userId == t.userId);
                    n ? n.checked = r.agreeExemptionAgreement : u.push({
                        userId: t.userId,
                        checked: r.agreeExemptionAgreement
                    });
                    f.saveObject(u)
                };
            (function() {
                r.close = o;
                r.saveTemplate = s;
                r.showSelected = h;
                r.viewExemptionAgreement = c;
                r.onExemptionAgreementCheck = e;
                r.showExemptionAgreement = !1;
                r.agreeExemptionAgreement = !1;
                r.expandedNodes = []
            })()
        }
    }
}]);
emrModule.directive("patientNewEmrEditView", ["$log", "$timeout", "$window", "$modal", "$q", "appNav", "loginContext", "practiceSvc", "schedulerUtil", "$sce", "systemConfigUtil", "printTemplateUtil", "constants", "patientUtil", "providerUtil", "emrCustomizeEditUtil", "enums", "emrUtil", "systemConfigSvc", "layoutTemplateSvc", "operationLogsvc", "printUtil", function(n, t, i, r, u, f, e, o, s, h, c, l, a, v, y, p, w, b, k, d, g, nt) {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        controller: "PatientNewEmrEditCtrl",
        templateUrl: "/app/emr/views/patient-new-emr-edit-view.html",
        link: function(n, i) {
            var v = null,
                w = null,
                b = null,
                k = null,
                it = {
                    desc1: "以下为PICC中国人民保险【“即刻”无忧】保险必填项，为了保障您的权益，请务必在植体出库后72小时内填写完整并下载PDF，在【开放平台】-【PICC即刻SMILE】中上传至该患者名下。",
                    desc2: "以下为PICC中国人民保险【“即刻”无忧】保险理赔申请必填项，为了保障您的权益，请务必填写完整并下载PDF，同时在【开放平台】下载并完善【理赔申请】，将该PDF与理赔申请单打包上传至该患者名下。"
                },
                ht = function() {
                    angular.forEach(n.templateItemGridList, function(t) {
                        $(t.gridId).kendoGrid({
                            dataSource: {
                                data: null,
                                schema: {
                                    model: {
                                        fields: {
                                            itemName: {
                                                type: "string"
                                            }
                                        }
                                    }
                                }
                            },
                            height: 250 * t.height,
                            scrollable: !0,
                            selectable: "single",
                            sortable: {
                                mode: "single",
                                allowUnsort: !1
                            },
                            columns: [{
                                field: "itemName",
                                title: t.gridName,
                                width: "100px"
                            }]
                        });
                        var i = angular.copy(t.gridId);
                        $(i).on("dblclick", "tr.k-state-selected", n.doubleClickTemplate)
                    })
                },
                ct = function(t) {
                    n.$apply(function() {
                        var i = t.currentTarget.innerText,
                            r, u;
                        for (n.currentFocusControlName || (n.currentFocusControlName = "主诉"), n.currentFocusControlName == "主诉" ? n.currentMedicalRecord.chiefComplaint = n.currentMedicalRecord.chiefComplaint + i : n.currentFocusControlName == "现病史" ? n.currentMedicalRecord.history = n.currentMedicalRecord.history + i : n.currentFocusControlName == "既往史" ? n.currentMedicalRecord.pastHistory = n.currentMedicalRecord.pastHistory + i : n.currentFocusControlName == "口腔检查" ? n.selectedIndex != null ? n.currentMedicalRecord.oralCheckRecordList[n.selectedIndex].description = n.currentMedicalRecord.oralCheckRecordList[n.selectedIndex].description + i : angular.forEach(n.currentMedicalRecord.oralCheckRecordList, function(n) {
                                n.description = n.description + i
                            }) : n.currentFocusControlName == "辅助检查" ? n.selectedIndex != null ? n.currentMedicalRecord.radiologyCheckRecordList[n.selectedIndex].description = n.currentMedicalRecord.radiologyCheckRecordList[n.selectedIndex].description + i : angular.forEach(n.currentMedicalRecord.radiologyCheckRecordList, function(n) {
                                n.description = n.description + i
                            }) : n.currentFocusControlName == "诊断" ? n.selectedIndex != null ? n.currentMedicalRecord.diagnoseRecordList[n.selectedIndex].diagnose = n.currentMedicalRecord.diagnoseRecordList[n.selectedIndex].diagnose + i : angular.forEach(n.currentMedicalRecord.diagnoseRecordList, function(n) {
                                n.diagnose = n.diagnose + i
                            }) : n.currentFocusControlName == "治疗计划" ? n.selectedIndex != null ? n.currentMedicalRecord.treatmentPlanList[n.selectedIndex].planContent = n.currentMedicalRecord.treatmentPlanList[n.selectedIndex].planContent + i : angular.forEach(n.currentMedicalRecord.treatmentPlanList, function(n) {
                                n.planContent = n.planContent + i
                            }) : n.currentFocusControlName == "治疗建议" ? n.selectedIndex != null ? n.currentMedicalRecord.treatmentAdviceList[n.selectedIndex].content = n.currentMedicalRecord.treatmentAdviceList[n.selectedIndex].content + i : angular.forEach(n.currentMedicalRecord.treatmentAdviceList, function(n) {
                                n.content = n.content + i
                            }) : n.currentFocusControlName == "治疗" ? n.selectedIndex != null ? n.currentMedicalRecord.cureRecordList[n.selectedIndex].cure = n.currentMedicalRecord.cureRecordList[n.selectedIndex].cure + i : angular.forEach(n.currentMedicalRecord.cureRecordList, function(n) {
                                n.cure = n.cure + i
                            }) : n.currentFocusControlName == "医嘱" && (n.currentMedicalRecord.advice = n.currentMedicalRecord.advice + i), r = 0; r < n.templateItemGridList.length; ++r) n.selectTabName && n.selectTabName == n.templateItemGridList[r].tabName && (u = $(n.templateItemGridList[r].gridId).data("kendoGrid"), u.clearSelection())
                    })
                },
                lt = function(t) {
                    f.switchState(t, {
                        patientId: n.patientId
                    })
                },
                at = function() {
                    b = i.find("#doctor").kendoNameCodeFilterComboBox({
                        dataSource: n.doctors,
                        filter: "contains",
                        placeholder: "请选择医生",
                        dataTextField: "name",
                        dataValueField: "id",
                        select: function() {
                            t(function() {
                                n.currentMedicalRecord.doctorName = b.text();
                                n.currentMedicalRecord.doctorId = b.value()
                            })
                        }
                    }).data("kendoNameCodeFilterComboBox");
                    n.currentMedicalRecord.doctorId > 0 ? h(n.currentMedicalRecord.doctorId, "doctor") : e.isDoctor && h(e.providerId, "doctor")
                },
                vt = function() {
                    e.providerJob == "牙医助理" ? n.superiorDoctor = n.doctors : e.isIntern && (n.superiorDoctor = n.doctors.filter(function(n) {
                        return !n.isIntern && n.show && n.userID && n.userID > 0
                    }));
                    k = i.find("#superiorDoctor").kendoNameCodeFilterComboBox({
                        dataSource: n.superiorDoctor,
                        filter: "contains",
                        placeholder: "请选择医生",
                        dataTextField: "name",
                        dataValueField: "id",
                        select: function() {
                            t(function() {
                                n.currentMedicalRecord.instructorName = k.text();
                                n.currentMedicalRecord.instructorId = k.value()
                            })
                        }
                    }).data("kendoNameCodeFilterComboBox");
                    n.currentMedicalRecord.instructorId ? h(n.currentMedicalRecord.instructorId, "superiorDoctor") : n.isShowSuperiorDoctor && (n.currentProvider ? h(n.currentProvider.instructorId, "superiorDoctor") : e.providerJob == "牙医助理" ? h(e.relatedProviderId, "superiorDoctor") : e.isIntern && n.getCurrentProvider().then(function() {
                        h(n.currentProvider.instructorId, "superiorDoctor")
                    }))
                },
                yt = function() {
                    i.find("#nurse").kendoNameCodeFilterComboBox({
                        dataSource: n.nurses,
                        filter: "contains",
                        placeholder: "请选择助手",
                        dataTextField: "name",
                        dataValueField: "id"
                    });
                    n.currentMedicalRecord.nurseId > 0 && h(n.currentMedicalRecord.nurseId, "nurse")
                },
                rt = function() {
                    var t = n.historyAppts;
                    i.find("#appoint").kendoDropDownList({
                        dataSource: t,
                        placeholder: "请选择",
                        valueTemplate: '<span class="k-state-default">#: data.startTimeStr #<\/span>',
                        template: '<span class="k-state-default">#: data.startTimeStr #<\/span>',
                        dataValueField: "id",
                        select: function(t) {
                            var r = this.dataItem(t.item.index()),
                                u;
                            tt(r.id > 0 ? !1 : !0);
                            n.currentMedicalRecord.appointId = r.id;
                            n.currentMedicalRecord.appointDateTime = r.startTime;
                            n.currentMedicalRecord.doctorName = r.doctorName;
                            n.currentMedicalRecord.doctorId = r.doctorId;
                            u = i.find("#doctor").data("kendoNameCodeFilterComboBox");
                            u && u.value(r.doctorId);
                            n.$apply()
                        }
                    });
                    n.currentMedicalRecord.id > 0 && h(n.currentMedicalRecord.appointId, "appoint")
                },
                h = function(t, r, u) {
                    var f = null,
                        e;
                    r == "doctor" && (f = _.findIndex(n.doctors, function(n) {
                        return n.id == t
                    }));
                    r == "superiorDoctor" && (f = _.findIndex(n.superiorDoctor, function(n) {
                        return n.id == t
                    }));
                    r == "appoint" && (f = u ? _.findIndex(u, function(n) {
                        return n.id == t
                    }) : _.findIndex(n.historyAppts, function(n) {
                        return n.id == t
                    }));
                    r == "nurse" && (f = _.findIndex(n.nurses, function(n) {
                        return n.id == t
                    }));
                    f >= 0 && (e = i.find("#" + r).data("kendoNameCodeFilterComboBox"), r == "appoint" && (e = i.find("#" + r).data("kendoDropDownList")), e && e.select(f))
                },
                ut = function() {
                    v ? o.getArchive().success(function(n) {
                        v.dataSource.data(n)
                    }) : o.getArchive().success(function(t) {
                        var u = $("#archive"),
                            r = n.currentMedicalRecord.archive;
                        v = u.kendoMultiSelect({
                            dataSource: t,
                            dataTextField: "itemName",
                            dataValueField: "itemName",
                            change: function() {
                                var t = i.find("#archive").data("kendoMultiSelect");
                                t && t.value() != "" && (n.currentMedicalRecord.archive = t.value().join());
                                n.$apply();
                                Ares.sensors.trackDropDownEvent("PatientNewEmrEdit", "标签")
                            }
                        }).data("kendoMultiSelect");
                        r && v && v.value(r.split(","))
                    })
                },
                pt = function() {
                    var n = r.open({
                        animation: !0,
                        backdrop: "static",
                        template: "<emr-print-configuration-view><\/emr-print-configuration-view>",
                        controller: "emrPrintConfigurationCtrl",
                        size: "lg",
                        resolve: {
                            host: function() {
                                return {
                                    template: "emr"
                                }
                            }
                        }
                    });
                    n.result.then(function(n) {
                        ft(n)
                    })
                },
                ft = function(t) {
                    n.printTemplateConfig = {
                        configName: "emr",
                        coments: "emrPrint"
                    };
                    var i = t && t.configName == "emr" ? u.when(t.configValue) : c.getConfigValue("emr");
                    i.then(function(t) {
                        if (t && t != "") {
                            var i = t;
                            n.printTemplateConfig.isHide = !1;
                            n.printTemplateConfig.templateCode = i;
                            i.indexOf("EMR") < 0 && (n.printTemplateConfig.isHide = !0);
                            l.getTemplateByCode(i).then(function(t) {
                                n.printTemplate = t
                            })
                        } else n.printTemplateConfig.isHide = !0
                    })
                },
                wt = function() {
                    var t = i.find("#nurse").data("kendoNameCodeFilterComboBox");
                    t && t.select() != -1 && (n.currentMedicalRecord.nurseName = t.text(), n.currentMedicalRecord.nurseId = t.value())
                },
                bt = function() {
                    var n = i.find("#doctor").data("kendoNameCodeFilterComboBox");
                    return n.select()
                },
                kt = function() {
                    var t = i.find("#doctor").data("kendoNameCodeFilterComboBox");
                    t && t.select() != -1 && (n.currentMedicalRecord.doctorName = t.text(), n.currentMedicalRecord.doctorId = t.value())
                },
                dt = function() {
                    var t = i.find("#superiorDoctor").data("kendoNameCodeFilterComboBox");
                    t && t.select() != -1 && (n.currentMedicalRecord.instructorName = t.text(), n.currentMedicalRecord.instructorId = t.value())
                },
                et = function(n) {
                    return n != null && (_.each(n.oralCheckRecordList, function(n) {
                        n != null && n.fdiToothCodesArray != null && (n.description = n.fdiToothCodesArray.join(",") + n.description)
                    }), _.each(n.radiologyCheckRecordList, function(n) {
                        n != null && n.fdiToothCodesArray != null && (n.description = n.fdiToothCodesArray.join(",") + n.description)
                    }), _.each(n.cureRecordList, function(n) {
                        n != null && n.fdiToothCodesArray != null && (n.cure = n.fdiToothCodesArray.join(",") + n.cure)
                    }), _.each(n.diagnoseRecordList, function(n) {
                        n != null && n.fdiToothCodesArray != null && (n.diagnose = n.fdiToothCodesArray.join(",") + n.diagnose)
                    }), _.each(n.treatmentPlanList, function(n) {
                        n != null && n.fdiToothCodesArray != null && (n.planContent = n.fdiToothCodesArray.join(",") + n.planContent)
                    }), _.each(n.treatmentAdviceList, function(n) {
                        n != null && n.fdiToothCodesArray != null && (n.content = n.fdiToothCodesArray.join(",") + n.content)
                    }), n.oralCheckRecordList = _.pluck(n.oralCheckRecordList, "description").join("|"), n.radiologyCheckRecordList = _.pluck(n.radiologyCheckRecordList, "description").join("|"), n.cureRecordList = _.pluck(n.cureRecordList, "cure").join("|"), n.diagnoseRecordList = _.pluck(n.diagnoseRecordList, "diagnose").join("|"), n.treatmentPlanList = _.pluck(n.treatmentPlanList, "planContent").join("|"), n.treatmentAdviceList = _.pluck(n.treatmentAdviceList, "content").join("|"), n.nurseId || (n.nurseId = "0")), _.pick(n, "oralCheckRecordList", "radiologyCheckRecordList", "cureRecordList", "diagnoseRecordList", "treatmentPlanList", "treatmentAdviceList", "advice", "archive", "chiefComplaint", "doctorId", "firstVisit", "history", "nurseId", "pastHistory")
                },
                gt = function() {
                    n.smallLayOut = !n.smallLayOut
                },
                ni = function(t, r) {
                    var u = i.find("#appoint").data("kendoDropDownList");
                    u != null && (r ? u.dataSource.data(r) : u.dataSource.data(n.historyAppts), h(t.id, "appoint", r), r || h(t.doctorId, "doctor"))
                },
                ti = function() {
                    return n.printTemplateConfig.isHide || n.currentMedicalRecord && n.currentMedicalRecord.id == 0 || n.currentMedicalRecord && n.currentMedicalRecord.id > 0 && n.isChanged || n.currentMedicalRecord && n.currentMedicalRecord.workflowStatus == 1
                },
                ii = function() {
                    var t = angular.copy(n.currentMedicalRecord);
                    return t.oralCheckRecordList = _.filter(t.oralCheckRecordList, function(n) {
                        return n.description || n.fdiToothCodesArray.length > 0
                    }), t.radiologyCheckRecordList = _.filter(t.radiologyCheckRecordList, function(n) {
                        return n.description || n.fdiToothCodesArray.length > 0
                    }), t.diagnoseRecordList = _.filter(t.diagnoseRecordList, function(n) {
                        return n.diagnose || n.fdiToothCodesArray.length > 0
                    }), t.treatmentPlanList = _.filter(t.treatmentPlanList, function(n) {
                        return n.planContent || n.fdiToothCodesArray.length > 0
                    }), t.cureRecordList = _.filter(t.cureRecordList, function(n) {
                        return n.cure || n.fdiToothCodesArray.length > 0
                    }), t.treatmentAdviceList = _.filter(t.treatmentAdviceList, function(n) {
                        return n.content || n.fdiToothCodesArray.length > 0
                    }), t
                },
                ri = function() {
                    c.getConfigValue(c.configKeys.AllowEditToothFDI).then(function(t) {
                        n.allowEditToothFDI = t ? t : !1
                    })
                },
                ui = function() {
                    var r = ot(),
                        u = moment(r.value()).format("HH:mm"),
                        f = moment(r.value()).add(30, "m").format("HH:mm"),
                        e = n.tempHistoryAppts || n.historyAppts,
                        t = _.find(e, {
                            id: -2
                        }),
                        o;
                    t && (t.startTime = moment(t.startTime).format("YYYY-MM-DD " + u), t.startTimeStr = moment(t.startTime).format("YYYY年MM月DD日 " + u), t.endTime = moment(t.endTime).format("YYYY-MM-DD " + f), t.endTimeStr = moment(t.endTime).format("YYYY年MM月DD日 " + f), o = i.find("#appoint").data("kendoDropDownList"), o.dataSource.data(e))
                },
                tt = function(n) {
                    var t = ot();
                    t && t.enable(n)
                },
                ot = function() {
                    return w || (w = i.find("#timepicker").data("kendoTimePicker")), w
                },
                fi = function() {
                    s.loadSchedulerConfig().then(function(t) {
                        n.timePickerOption = t && t.timeSlotUnit ? {
                            interval: t.timeSlotUnit
                        } : {
                            interval: 30
                        }
                    });
                    vi()
                },
                ei = function() {
                    ri();
                    ht();
                    fi();
                    n.isShowSuperiorDoctor = e.providerJob == "牙医助理" || e.isIntern ? !0 : !1;
                    n.isShowEmrTemplateHref = e.providerJob == "医生" && e.isIntern ? !1 : !0;
                    t(function() {
                        tt(!1)
                    }, 100)
                },
                oi = function(n) {
                    var t = i.find('div[emr-field-name="' + n + '"]').find("input[type=text],input[type=radio],input[type=checkbox],textarea,select").filter(":visible:first");
                    t.focus()
                },
                si = function(n) {
                    n.newItem = n.newItem ? "" : n.parent
                },
                hi = function() {
                    var t = r.open({
                        animation: !0,
                        backdrop: "static",
                        template: "<patient-new-emr-edit-template-choice-view><\/patient-new-emr-edit-template-choice-view>",
                        controller: "patientNewEmrEditTemplateChoiceCtrl",
                        size: "sm",
                        resolve: {
                            host: function() {
                                return {
                                    treeControl: n.templateTreeControl,
                                    isEmrCustomTemplateEnabled: n.isEmrCustomTemplateEnabled,
                                    currentMedicalRecord: n.currentMedicalRecord,
                                    layoutTemplate: n.emrLayoutTemplate
                                }
                            }
                        }
                    });
                    t.result.then(function(t) {
                        n.currentMedicalRecord = t
                    });
                    Ares.sensors.track("PatientNewEmr", {
                        OperationType: "病历模板"
                    })
                },
                ci = function(n) {
                    var t = null;
                    return n.templateName === "“即刻”无忧种植处置（72小时内上传）" ? t = it.desc1 : n.templateName === "“即刻”无忧种植处置理赔申请" && (t = it.desc2), t
                },
                li = function(t) {
                    n.templateDesc = ci(t);
                    n.currentMedicalRecord.firstVisit = t.templateCode == a.firstVisitTemplateCode ? !0 : t.templateCode == a.secondVisitTemplateCode ? !1 : null;
                    ai(t)
                },
                ai = function(t) {
                    var f = i.find("#customizeMedicalRecord"),
                        r = angular.copy(t),
                        e = new RegExp(/^[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}$/),
                        u;
                    r.templateCode !== "firstEmr" && r.templateCode !== "secondEmr" && e.test(r.templateCode.toLowerCase()) ? (u = [], _.forEach(r.rootFields, function(n) {
                        n.srcFieldCode.indexOf("Sys_") === -1 && u.push(n.srcFieldCode);
                        _.forEach(n.subFields, function(n) {
                            n.srcFieldCode.indexOf("Sys_") === -1 && u.push(n.srcFieldCode)
                        })
                    }), u.length > 0 && d.getChildFieldByParentCodes(u).success(function(t) {
                        t && t.length > 0 && _.forEach(r.rootFields, function(n) {
                            _.forEach(n.subFields, function(n) {
                                var i = _.filter(t, function(t) {
                                    return t.fieldCode == n.srcFieldCode
                                });
                                i && i.length > 0 && (n.seqNum = i[0].seqNum);
                                n.subFields && n.subFields.length > 0 && _.forEach(n.subFields, function(n) {
                                    var i = _.filter(t, function(t) {
                                        return t.fieldCode == n.srcFieldCode
                                    });
                                    i && i.length > 0 && (n.seqNum = i[0].seqNum)
                                })
                            })
                        });
                        p.buildEditEmrHtml(r, n, f);
                        n.emrLayoutTemplate = r;
                        n.setEmrTemplateFieldsArray();
                        n.setCurrentEMRTemplateSetting()
                    })) : (p.buildEditEmrHtml(r, n, f), n.emrLayoutTemplate = r, n.setEmrTemplateFieldsArray(), n.setCurrentEMRTemplateSetting())
                },
                vi = function() {
                    n.IsAloneSaveOralCheckSymptom = !1;
                    c.getConfigValue(c.configKeys.IsAloneSaveOralCheckSymptom).then(function(t) {
                        n.IsAloneSaveOralCheckSymptom = t ? t : !1
                    })
                },
                yi = function(t) {
                    n.toothSynchronization(t)
                },
                pi = function(t) {
                    n.deleteToothCode(t)
                },
                wi = function() {
                    var t = (n.patient ? n.patient.name : "患者") + "的电子病历";
                    nt.printWithLocal(n.printTemplateConfig.templateCode, n.printTemplate.templateName, t);
                    st()
                },
                st = function() {
                    var t = _.find(n.availableLayoutTemplates, function(t) {
                            return t.templateCode === n.currentMedicalRecord.layoutTemplateCode
                        }),
                        i = [{
                            ModuleLevelOne: "病历管理",
                            ModuleLevelTwo: "打印病历",
                            OperationType: "打印",
                            patientId: n.currentMedicalRecord.patientId,
                            changeFields: [{
                                field: "病历类型",
                                newValue: t.templateName
                            }, {
                                field: "就诊日期",
                                newValue: n.currentMedicalRecord.appointDateTime
                            }]
                        }];
                    g.batchAddOperationLogs(i)
                };
            (function() {
                n.disablePrint = ti;
                n.initPrint = ft;
                n.printTemplateConfig = {};
                n.goToList = lt;
                n.selectDropDown = h;
                n.doubleClickTemplate = ct;
                n.initArchiveDropdown = ut;
                n.toPrint = pt;
                n.setNurse = wt;
                n.setDoctor = kt;
                n.setSuperiorDoctor = dt;
                n.getDoctor = bt;
                n.smallLayOut = !1;
                n.collapsedSidebar = gt;
                n.refreshApptDropDown = ni;
                n.onTimePickerChanged = ui;
                n.isEnabledTimePicker = tt;
                n.scrollIntoView = oi;
                n.changeCategory = si;
                n.selectTemplate = hi;
                n.setLayoutTemplate = li;
                n.onSyncToothCode = yi;
                n.onDeleteToothCode = pi;
                n.printLog = st;
                n.print = wi;
                ei();
                n.$watch("nurses", function() {
                    n.nurses && (yt(), ut())
                });
                n.$watch("doctors", function() {
                    n.doctors && (at(), n.isShowSuperiorDoctor && vt())
                });
                n.$watch("historyAppts", function() {
                    n.historyAppts && rt()
                });
                n.$watch("emrLayoutTemplate", function() {
                    n.historyAppts && n.historyAppts.length > 0 && rt()
                });
                n.$watch("currentMedicalRecord.firstVisit", function() {
                    n.currentMedicalRecord && (n.isAllowSynchronization && n.Synching == !1 && n.recordTooth != null ? n.formatMedicalRecord(n.currentMedicalRecord).then(n.toothSynchronization) : n.formatMedicalRecord(n.currentMedicalRecord), n.getEMRTemplates())
                });
                n.$watch("currentMedicalRecord.doctorId", function() {
                    n.currentMedicalRecord && y.getProviderEmployeeSignature(n.providerPictures, n.currentMedicalRecord.doctorId, n).then(function(t) {
                        n.providerEmployeeSignature = t
                    })
                });
                n.$watch("currentMedicalRecord", function() {
                    if (n.currentMedicalRecord) {
                        if (n.currentMedicalRecord.id > 0 && !n.isUpdating && n.originalMedicalRecord) {
                            var t = angular.copy(n.originalMedicalRecord),
                                i = angular.copy(n.currentMedicalRecord);
                            i = et(i);
                            t = et(t);
                            n.isChanged = _.isEqual(t, i) ? !1 : !0
                        }
                        n.printCurrentMedicalRecord = ii()
                    }
                }, !0)
            })()
        }
    }
}]);
emrModule.directive("patientNewEmrExemptionAgreementView", ["$timeout", function() {
    "use strict";
    return {
        replace: !0,
        templateUrl: "/app/emr/views/patient-new-emr-exemption-agreement-view.html",
        link: function() {
            (function() {})()
        }
    }
}]);
emrModule.directive("patientNewEmrTemplateSaveDiseaseChoice", ["$log", "$timeout", function(n, t) {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/emr/views/patient-new-emr-template-save-disease-choice.html",
        link: function(n, i) {
            t(function() {
                Ares.centerModal(i.closest(".modal-dialog"))
            }, 100)
        }
    }
}]);
emrModule.directive("patientNewEmrTemplateSave", ["$log", "$timeout", "$q", "$modal", "loginContext", "dataDicSvc", "patientSvc", "aresDialog", "officeOptionSvc", function(n, t, i, r, u, f, e, o, s) {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/emr/views/patient-new-emr-template-save.html",
        link: function(n, f) {
            var h = function() {
                    if (n.currentEMRTemplate.itemName = n.currentEMRTemplate.templateName, n.templateTreeControl.checkDuplicateNameSibling(n.currentEMRTemplate)) {
                        o.warn("提示", "该模板类别已存在同名的子目录或模板");
                        return
                    }
                    if (n.isSaving = !0, n.currentEMRTemplate.diseaseId === null || typeof n.currentEMRTemplate.diseaseId == "undefined") {
                        o.warn("提示", "请选择模板类别！");
                        return
                    }
                    e.createEMRTemplate(n.currentEMRTemplate).success(function() {
                        o.info("信息", "模板保存成功！");
                        n.cancel()
                    }).error(function() {
                        o.warn("提示", "保存失败！");
                        n.isSaving = !1
                    })
                },
                c = function() {
                    var t = i.defer();
                    return s.getOfficeOption(s.optionKeys.IsEmrCustomTemplateEnabled).then(function(i) {
                        i == "1" && (n.isEmrCustomTemplateEnabled = !0);
                        t.resolve(!0)
                    }), t.promise
                },
                l = function() {
                    var t = r.open({
                        animation: !0,
                        backdrop: "static",
                        template: "<patient-new-emr-template-save-disease-choice><\/patient-new-emr-template-save-disease-choice>",
                        controller: "patientNewEmrTemplateSaveDiseaseChoiceCtrl",
                        size: "sm",
                        resolve: {
                            host: function() {
                                return {
                                    treeControl: n.templateTreeControl
                                }
                            }
                        }
                    });
                    t.result.then(function(t) {
                        n.currentEMRTemplate.diseaseId = t.id;
                        n.currentEMRTemplateDiseaseBreadcrumb = t.breadcrumb;
                        t.departmentName === "我的模板" && (n.currentEMRTemplate.userId = u.userId)
                    })
                };
            (function() {
                c().then(function() {
                    n.ok = h
                });
                n.showDiseaseChoiceDlg = l
            })();
            t(function() {
                Ares.centerModal(f.closest(".modal-dialog"))
            }, 5)
        }
    }
}]);
emrModule.directive("patientNewEmrView", ["$log", "$q", "$timeout", "loginContext", "appNav", "printUtil", "patientSvc", "aresDialog", "permissionProvider", "systemConfigUtil", "$modal", "emrCustomizeDisplayUtil", "systemConfigSvc", "operationLogsvc", "printTemplateUtil", function(n, t, i, r, u, f, e, o, s, h, c, l, a, v, y) {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        controller: "PatientNewEmrCtrl",
        templateUrl: "/app/emr/views/patient-new-emr-view.html",
        link: function(n, t) {
            var l = function(t) {
                    t == "patientMedicalRecord.createRecord" ? u.goToCreateEMR(n.patientId, {
                        patientId: n.patientId
                    }) : u.switchState(t, {
                        patientId: n.patientId
                    })
                },
                p = function(t) {
                    t.isDocument ? n.openPatientDocEditDialog(t.medicalRecordId) : w(t) ? t.isAllowEdit == 1 ? u.switchState("patientgeneralMedicalRecords.patientEmr.edit", {
                        patientId: n.patientId,
                        medicalRecordId: t.medicalRecordId
                    }) : t.isAllowEdit == 2 ? o.info("提醒", "该病历超出病历时限范围，不允许修改！") : e.isAllowEditMedicalRecordByTimeLimit(t.medicalRecordId).success(function(i) {
                        i ? (t.isAllowEdit = 1, u.switchState("patientgeneralMedicalRecords.patientEmr.edit", {
                            patientId: n.patientId,
                            medicalRecordId: t.medicalRecordId
                        })) : (t.isAllowEdit = 2, o.info("提醒", "该病历超出病历时限范围，不允许修改！"))
                    }) : o.info("提醒", "当前用户没有权限编辑该病历！")
                },
                w = function(n) {
                    return n.recordCreatedUser == r.userId || n.doctorId == r.providerId || s.isAllowed("patientMedicalRecord.alterOther") ? !0 : !1
                },
                b = function(n) {
                    i(function() {
                        var i = t.find("." + n.className).height() - 40 + "px";
                        n.detailHeight = i
                    }, 300)
                },
                k = function(t, r) {
                    t == "hardTissue" ? (i(function() {
                        l("patientgeneralMedicalRecords.patientGeneralExam.view", {
                            patientId: n.patientId,
                            examId: r
                        })
                    }, 200), u.goToHardTissue(n.patientId)) : t == "perioExam" ? (i(function() {
                        l("patientgeneralMedicalRecords.patientPerioExam.view", {
                            patientId: n.patientId,
                            examId: r
                        })
                    }, 200), u.goToPatient(n.patientId, "perioExamHistory")) : t == "imaging" ? u.goToImaging(n.patientId, "imagingHistory", {
                        apptId: r
                    }) : t == "prescription" ? u.goToPrescription(n.patientId) : t == "patientDocument" ? u.goToPatientDocument(n.patientId, "patientDocumentHistory", {
                        apptId: r
                    }) : t == "outprocess" ? u.goToOutprocess(n.patientId) : t == "patientCharge" ? u.goToCharge(n.patientId, r) : t == "followup" && u.goToPatient(n.patientId, "followupHistory")
                },
                d = function() {
                    n.medicalRecordId > 0 && i(function() {
                        var r = "#mid" + n.medicalRecordId,
                            i = t.find(r);
                        i && i.length > 0 && i[0].scrollIntoView()
                    }, 500)
                },
                g = function() {
                    h.getConfigValue(h.configKeys.AllowEditToothFDI).then(function(t) {
                        n.allowEditTooth = t ? t : !1
                    });
                    ut()
                },
                nt = function(n) {
                    var t = c.open({
                        animation: !0,
                        backdrop: "static",
                        template: "<operation-log-list-view><\/operation-log-list-view>",
                        controller: "OperationLogListCtrl",
                        size: "lg",
                        windowClass: "operation-log-dialog",
                        resolve: {
                            host: function() {
                                return {
                                    id: n,
                                    type: "MedicalRecord"
                                }
                            }
                        }
                    })
                },
                tt = function(i) {
                    var r = n.medicalRecords.filter(function(n) {
                        return n.workflowStatus != 1
                    });
                    i.length === 0 || r.length === 0 ? o.info("提示", "没有可以打印的病历") : n.getAllMedicalRecordDetails().then(function() {
                        n.refreshTemplate();
                        var r = setInterval(function() {
                            var e = t.find(".emrPrintTemplateRenderFinishedFlag"),
                                u;
                            e.length == n.medicalRecords.length && (clearInterval(r), u = (n.patient ? n.patient.name : "患者") + "的全部电子病历", f.printWithLocal(JSON.stringify(i), n.printTemplate.templateName, u), a(n.medicalRecords))
                        }, 200)
                    })
                },
                it = function(t) {
                    var u = n.medicalRecords.filter(function(n) {
                            return n.workflowStatus != 1
                        }),
                        r;
                    t && u.length !== 0 ? (r = n.medicalRecords.find(n => n.id == t), n.showDetail(r, null, !0).then(function() {
                        n.refreshTemplate();
                        i(function() {
                            var i = (n.patient ? n.patient.name : "患者") + "的电子病历";
                            f.printWithLocal('["#' + t + '"]', n.printTemplate.templateName, i);
                            a([r])
                        }, 500)
                    })) : o.info("提示", "没有可以打印的病历")
                },
                rt = function(t) {
                    n.diseaseProofMedicalRecord = angular.copy(t);
                    var r = "A5EMRDiseaseProofTemplate1";
                    i(function() {
                        y.getTemplateByCode(r).then(function(t) {
                            var i = (n.patient ? n.patient.name : "患者") + "的疾病证明书";
                            f.printWithLocal("#" + r, t.templateName, i)
                        })
                    }, 500)
                },
                ut = function() {
                    n.IsAloneSaveOralCheckSymptom = !1;
                    h.getConfigValue(h.configKeys.IsAloneSaveOralCheckSymptom).then(function(t) {
                        n.IsAloneSaveOralCheckSymptom = t ? t : !1
                    })
                },
                a = function(t) {
                    var i = _.map(t, function(t) {
                        var i = _.find(n.layoutTemplates, function(n) {
                            return n.templateCode === t.layoutTemplateCode
                        });
                        return {
                            ModuleLevelOne: "病历管理",
                            ModuleLevelTwo: "打印病历",
                            OperationType: "打印",
                            patientId: t.patientId,
                            changeFields: [{
                                field: "病历类型",
                                newValue: i.templateName
                            }, {
                                field: "就诊日期",
                                newValue: t.appointDateTime
                            }]
                        }
                    });
                    v.batchAddOperationLogs(i)
                };
            (function() {
                n.setHeight = b;
                n.editEMR = p;
                n.switchState = l;
                n.goToTab = k;
                n.autoScroll = d;
                n.printAll = tt;
                n.print = it;
                n.showEmrChangeLog = nt;
                n.printDiseaseProofTemplate = rt;
                g()
            })()
        }
    }
}]);
var emr;
(function() {
    "use strict";
    var n = function() {
        function n() {
            this.restrict = "E";
            this.replace = !0;
            this.template = '\n            <div style="width: 100%; height: 100%;">\n                <ares-new-home-view target-route="emr.list"><\/ares-new-home-view>\n            <\/div>\n        '
        }
        return n.$inject = [], n
    }();
    emrModule.directive("ares3EmrManagementListView", Ares.tsDirective(n))
})(emr || (emr = {}));
var emr;
(function() {
    "use strict";
    var n = function() {
        function n() {
            this.restrict = "E";
            this.replace = !0;
            this.template = '\n            <div style="width: 100%; height: 100%;">\n                <ares-new-home-view target-route="emr.myList"><\/ares-new-home-view>\n            <\/div>\n        '
        }
        return n.$inject = [], n
    }();
    emrModule.directive("ares3EmrManagementMyListView", Ares.tsDirective(n))
})(emr || (emr = {}));
emrModule.directive("emrAdviceDisplayView", ["$log", "$timeout", function() {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/emr/views/emr-components/display/emr-advice-display-view.html",
        scope: {
            field: "=",
            currentValue: "=?"
        },
        link: function() {
            (function() {})()
        }
    }
}]);
emrModule.directive("emrChiefComplaintDisplayView", ["$log", "$timeout", function() {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/emr/views/emr-components/display/emr-chief-complaint-display-view.html",
        scope: {
            field: "=",
            currentValue: "=?",
            title: "="
        },
        link: function() {
            (function() {})()
        }
    }
}]);
emrModule.directive("emrCommentDisplayView", ["$log", "$timeout", function() {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/emr/views/emr-components/display/emr-comment-display-view.html",
        scope: {
            field: "=",
            currentValue: "=?"
        },
        link: function() {
            (function() {})()
        }
    }
}]);
emrModule.directive("emrCureRecordsDisplayView", ["$log", "$timeout", function() {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/emr/views/emr-components/display/emr-cure-records-display-view.html",
        scope: {
            field: "=",
            currentValue: "=?",
            isEmrCustomTemplateEnabled: "=?",
            allowEditTooth: "=?",
            allowToothFdi: "=?"
        },
        link: function() {
            (function() {})()
        }
    }
}]);
emrModule.directive("emrDiagnoseRecordsDisplayView", ["$log", "$timeout", function() {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/emr/views/emr-components/display/emr-diagnose-records-display-view.html",
        scope: {
            field: "=",
            currentValue: "=?",
            isEmrCustomTemplateEnabled: "=?",
            allowEditTooth: "=?",
            allowToothFdi: "=?"
        },
        link: function() {
            (function() {})()
        }
    }
}]);
emrModule.directive("emrDisplayHostView", ["$log", "$q", "$timeout", "emrCustomizeDisplayUtil", "enums", "dataDicSvc", "layoutTemplateSvc", function(n, t, i, r, u, f, e) {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/emr/views/emr-components/display/emr-display-host-view.html",
        scope: {
            medicalRecord: "=",
            isEmrCustomTemplateEnabled: "=?",
            allowEditTooth: "=?",
            allowToothFdi: "=?"
        },
        link: function(n, i) {
            var u = function() {
                    s(n.medicalRecord.layoutTemplateCode).then(function(t) {
                        var s = i.find(".medical-record-content"),
                            u = angular.copy(t),
                            h = new RegExp(/^[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}$/),
                            f;
                        u && u.templateCode !== "firstEmr" && u.templateCode !== "secondEmr" && h.test(u.templateCode.toLowerCase()) ? (f = [], _.forEach(u.rootFields, function(n) {
                            n.srcFieldCode.indexOf("Sys_") === -1 && f.push(n.srcFieldCode);
                            _.forEach(n.subFields, function(n) {
                                n.srcFieldCode.indexOf("Sys_") === -1 && f.push(n.srcFieldCode)
                            })
                        }), f.length > 0 && e.getChildFieldByParentCodes(f).success(function(t) {
                            t && t.length > 0 && (_.forEach(u.rootFields, function(n) {
                                _.forEach(n.subFields, function(n) {
                                    var i = _.filter(t, function(t) {
                                        return t.fieldCode == n.srcFieldCode
                                    });
                                    i && i.length > 0 && (n.seqNum = i[0].seqNum);
                                    n.subFields && n.subFields.length > 0 && _.forEach(n.subFields, function(n) {
                                        var i = _.filter(t, function(t) {
                                            return t.fieldCode == n.srcFieldCode
                                        });
                                        i && i.length > 0 && (n.seqNum = i[0].seqNum)
                                    })
                                })
                            }), angular.forEach(u.rootFields, function(n) {
                                o(n.subFields);
                                angular.forEach(n.subFields, function(n) {
                                    o(n.subFields)
                                })
                            }));
                            r.buildDisplayEmrHtml(u, n, s)
                        })) : r.buildDisplayEmrHtml(u, n, s)
                    })
                },
                o = function(n) {
                    var t = _.filter(n, function(n) {
                            return n.parentCode != "" && n.parentCode != undefined && (n.enableWhenFieldCode === "" || n.enableWhenFieldCode === undefined || n.enableWhenFieldCode === null)
                        }),
                        i = _.filter(n, function(n) {
                            return n.parentCode != "" && n.parentCode != undefined && n.enableWhenFieldCode != "" && n.enableWhenFieldCode != undefined && n.enableWhenFieldCode != null
                        });
                    angular.forEach(t, function(t) {
                        var r = _.filter(i, function(n) {
                                return t.fieldCode === n.enableWhenFieldCode
                            }),
                            u;
                        r && r.length > 0 && (u = r.length, angular.forEach(n, function(n) {
                            n.seqNum > t.seqNum && (n.seqNum = n.seqNum + u)
                        }), angular.forEach(r, function(i, r) {
                            angular.forEach(n, function(n) {
                                n.id === i.id && (i.seqNum = t.seqNum + r + 1)
                            })
                        }))
                    })
                },
                s = function(n) {
                    var i = t.defer();
                    return f.medicalRecordLayoutTemplateDic.load().then(function(t) {
                        var r = t,
                            u = _.find(r, function(t) {
                                return t.templateCode == n
                            });
                        i.resolve(u)
                    }), i.promise
                };
            (function() {
                var t = n.$watch("medicalRecord.layoutTemplateCode", function() {
                    u()
                });
                n.$on("medicalRecordSaved", function() {
                    u()
                });
                n.$on("$destroy", function() {
                    t && t()
                })
            })()
        }
    }
}]);
emrModule.directive("emrFreeCheckboxDisplayView", ["$log", "$timeout", function() {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/emr/views/emr-components/display/emr-free-checkbox-display-view.html",
        scope: {
            field: "=",
            currentValue: "=?"
        },
        link: function() {
            (function() {})()
        }
    }
}]);
emrModule.directive("emrFreeInputDisplayView", ["$log", "$timeout", function() {
    "use strict";
    return {
        restrict: "E",
        templateUrl: "/app/emr/views/emr-components/display/emr-free-input-display-view.html",
        scope: {
            field: "=",
            currentValue: "=?"
        },
        link: function() {
            (function() {})()
        }
    }
}]);
emrModule.directive("emrFreeNamedPictureDisplayView", ["$log", "$timeout", "$window", "$modal", "$q", "appNav", "loginContext", "patientSvc", "aresNotification", "practiceSvc", "eventAggregator", "$sce", "systemConfigUtil", "emrCustomizeEditUtil", "constants", "patientUtil", "providerUtil", function(n, t, i, r, u, f, e, o, s, h, c) {
    "use strict";
    return {
        restrict: "E",
        templateUrl: "/app/emr/views/emr-components/display/emr-free-named-picture-display-view.html",
        scope: {
            currentValue: "=?",
            field: "="
        },
        link: function(n) {
            var t = function() {
                    n.currentValue.fieldValue || (n.currentValue.fieldValue = n.field.defaultValue)
                },
                i = function(n, t) {
                    var i = {
                        imgUrl: n.filePath,
                        type: "image",
                        width: "500",
                        height: "400"
                    };
                    c.publish(c.events.PopupFlyout, i, t.delegateTarget)
                };
            (function() {
                t();
                n.showBigPicture = i
            })()
        }
    }
}]);
emrModule.directive("emrFreeNumberDisplayView", ["$log", "$timeout", function() {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/emr/views/emr-components/display/emr-free-number-display-view.html",
        scope: {
            field: "=",
            currentValue: "=?"
        },
        link: function() {
            (function() {})()
        }
    }
}]);
emrModule.directive("emrFreePictureDisplayView", ["$log", "$timeout", "$window", "$modal", "$q", "appNav", "loginContext", "patientSvc", "aresNotification", "practiceSvc", "eventAggregator", "$sce", "systemConfigUtil", "emrCustomizeEditUtil", "constants", "patientUtil", "providerUtil", function(n, t, i, r, u, f, e, o, s, h, c) {
    "use strict";
    return {
        restrict: "E",
        templateUrl: "/app/emr/views/emr-components/display/emr-free-picture-display-view.html",
        scope: {
            currentValue: "=?",
            field: "="
        },
        link: function(n) {
            var t = function() {
                    n.currentValue.fieldValue || (n.currentValue.fieldValue = n.field.defaultValue)
                },
                i = function(n, t) {
                    var i = {
                        imgUrl: n.filePath,
                        type: "image",
                        width: "500",
                        height: "400"
                    };
                    c.publish(c.events.PopupFlyout, i, t.delegateTarget)
                };
            (function() {
                t();
                n.showBigPicture = i
            })()
        }
    }
}]);
emrModule.directive("emrFreeRadioDisplayView", ["$log", "$timeout", function() {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/emr/views/emr-components/display/emr-free-radio-display-view.html",
        scope: {
            field: "=",
            currentValue: "=?"
        },
        link: function() {
            (function() {})()
        }
    }
}]);
emrModule.directive("emrFreeTextareaDisplayView", ["$log", "$timeout", function() {
    "use strict";
    return {
        restrict: "E",
        templateUrl: "/app/emr/views/emr-components/display/emr-free-textarea-display-view.html",
        scope: {
            field: "=",
            currentValue: "=?"
        },
        link: function() {
            (function() {})()
        }
    }
}]);
emrModule.directive("emrHistoryDisplayView", ["$log", "$timeout", function() {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/emr/views/emr-components/display/emr-history-display-view.html",
        scope: {
            field: "=",
            currentValue: "=?"
        },
        link: function() {
            (function() {})()
        }
    }
}]);
emrModule.directive("emrMedicalImageDisplayView", ["$sce", "eventAggregator", function(n, t) {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/emr/views/emr-components/display/emr-medical-image-display-view.html",
        scope: {
            field: "=?",
            currentValue: "=?",
            isPrint: "=?"
        },
        link: function(i) {
            i.sceControl = n.trustAsResourceUrl;
            i.field || (i.field = {
                level: 0
            });
            i.currentValue ? _.forEach(i.currentValue, function(n) {
                n.appointmentStartTime && !n.appointmentStartTimeStr && (n.appointmentStartTimeStr = moment(n.appointmentStartTime).format("YYYY/MM/DD"))
            }) : i.currentValue = [];
            var r = function(n, r) {
                    if (!i.isPrint) {
                        var u = {
                            imgUrl: n.mgmtType === 1 ? n.mediumUrl : n.fullImageUrl || n.fullUrl,
                            type: "image",
                            width: "500",
                            height: "300"
                        };
                        t.publish(t.events.PopupFlyout, u, r.delegateTarget)
                    }
                },
                u = function(n) {
                    return n.mgmtType === 1 ? n.thumbnailUrl : n.fullUrl || n.mediumUrl || n.thumbnailUrl
                };
            (function() {
                i.showBigPicture = r;
                i.printImg = u
            })()
        }
    }
}]);
emrModule.directive("emrOralCheckRecordsDisplayView", ["$log", "$timeout", "systemConfigSvc", function() {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/emr/views/emr-components/display/emr-oral-check-records-display-view.html",
        scope: {
            field: "=",
            currentValue: "=?",
            isEmrCustomTemplateEnabled: "=?",
            allowEditTooth: "=?",
            allowToothFdi: "=?"
        },
        link: function() {
            (function() {})()
        }
    }
}]);
emrModule.directive("emrPastHistoryDisplayView", ["$log", "$timeout", function() {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/emr/views/emr-components/display/emr-past-history-display-view.html",
        scope: {
            field: "=",
            currentValue: "=?"
        },
        link: function() {
            (function() {})()
        }
    }
}]);
emrModule.directive("emrRadiologyCheckRecordsDisplayView", ["$log", "$timeout", function() {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/emr/views/emr-components/display/emr-radiology-check-records-display-view.html",
        scope: {
            field: "=",
            currentValue: "=?",
            isEmrCustomTemplateEnabled: "=?",
            allowEditTooth: "=?",
            allowToothFdi: "=?"
        },
        link: function() {
            (function() {})()
        }
    }
}]);
emrModule.directive("emrTreatmentAdvicesDisplayView", ["$log", "$timeout", function() {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/emr/views/emr-components/display/emr-treatment-advices-display-view.html",
        scope: {
            field: "=",
            currentValue: "=?",
            allowEditTooth: "=?",
            allowToothFdi: "=?"
        },
        link: function() {
            (function() {})()
        }
    }
}]);
emrModule.directive("emrTreatmentPlansDisplayView", ["$log", "$timeout", function() {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/emr/views/emr-components/display/emr-treatment-plans-display-view.html",
        scope: {
            field: "=",
            currentValue: "=?",
            isEmrCustomTemplateEnabled: "=?",
            allowEditTooth: "=?",
            allowToothFdi: "=?"
        },
        link: function() {
            (function() {})()
        }
    }
}]);
emrModule.directive("emrAdviceEditView", ["$log", "$timeout", "$window", "$modal", "$q", "appNav", "loginContext", "practiceSvc", "schedulerUtil", "$sce", "systemConfigUtil", "printTemplateUtil", "constants", "patientUtil", "providerUtil", function() {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/emr/views/emr-components/edit/emr-advice-edit-view.html",
        scope: {
            field: "=",
            currentValue: "=?",
            onFocus: "=?",
            level: "="
        },
        link: function() {
            (function() {})()
        }
    }
}]);
emrModule.directive("emrArchiveEditView", ["$log", "$timeout", "$window", "$modal", "$q", "appNav", "loginContext", "practiceSvc", "schedulerUtil", "$sce", "systemConfigUtil", "printTemplateUtil", "constants", "patientUtil", "providerUtil", function(n, t, i, r, u, f, e, o) {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/emr/views/emr-components/edit/emr-archive-edit-view.html",
        scope: {
            field: "=",
            currentValue: "=?",
            onFocus: "=?"
        },
        link: function(n, t) {
            var i, f = function() {
                    var t = r.open({
                        animation: !0,
                        backdrop: "static",
                        template: "<system-setting-item-edit><\/system-setting-item-edit>",
                        controller: "SystemSettingItemEditCtrl",
                        resolve: {
                            host: function() {
                                return {
                                    itemType: "病历归档"
                                }
                            },
                            boxTitle: function() {
                                return ""
                            }
                        }
                    });
                    t.result.then(function() {
                        n.currentValue = "";
                        u()
                    })
                },
                u = function() {
                    i ? o.getArchive().success(function(n) {
                        i.dataSource.data(n)
                    }) : o.getArchive().success(function(r) {
                        var f = t.find(".archive-input"),
                            u = n.currentValue;
                        i = f.kendoMultiSelect({
                            dataSource: r,
                            dataTextField: "itemName",
                            dataValueField: "itemName",
                            change: function() {
                                i && (n.currentValue = i.value().join());
                                n.$apply();
                                Ares.sensors.trackDropDownEvent("PatientNewEmrEdit", "标签")
                            }
                        }).data("kendoMultiSelect");
                        u && i.value(u.split(","))
                    })
                };
            (function() {
                n.editArchive = f;
                u()
            })()
        }
    }
}]);
emrModule.directive("emrChiefComplaintEditView", ["$log", "$timeout", "$window", "$modal", "$q", "appNav", "loginContext", "practiceSvc", "schedulerUtil", "$sce", "systemConfigUtil", "printTemplateUtil", "constants", "patientUtil", "providerUtil", function() {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/emr/views/emr-components/edit/emr-chief-complaint-edit-view.html",
        scope: {
            field: "=",
            currentValue: "=?",
            isFirstVisit: "=?",
            onFocus: "=?",
            level: "="
        },
        link: function(n, t) {
            var i = function(n) {
                t.find(".item-tabs span").each(function(t) {
                    t === 0 ? angular.element(this).html('<i class="text">' + n + "词条<\/i>") : angular.element(this).html('<i class="text">' + n + "模板<\/i>")
                })
            };
            (function() {
                var t = n.$watch("isFirstVisit", function(n) {
                    n ? i("主诉") : i("复诊")
                });
                n.$on("$destroy", function() {
                    t && t()
                })
            })()
        }
    }
}]);
emrModule.directive("emrCommentEditView", ["$log", "$timeout", "$window", "$modal", "$q", "appNav", "loginContext", "practiceSvc", "schedulerUtil", "$sce", "systemConfigUtil", "printTemplateUtil", "constants", "patientUtil", "providerUtil", function() {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/emr/views/emr-components/edit/emr-comment-edit-view.html",
        scope: {
            field: "=",
            currentValue: "=?",
            onFocus: "=?"
        },
        link: function() {
            (function() {})()
        }
    }
}]);
emrModule.directive("emrCureRecordsEditView", ["$log", "$timeout", "$window", "$modal", "$q", "appNav", "loginContext", "chargeSvc", "practiceSvc", "schedulerUtil", "$sce", "systemConfigUtil", "printTemplateUtil", "constants", "patientUtil", "providerUtil", function() {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        controller: "EmrCureRecordsEditCtrl",
        templateUrl: "/app/emr/views/emr-components/edit/emr-cure-records-edit-view.html",
        scope: {
            field: "=",
            currentValue: "=?",
            isEmrCustomTemplateEnabled: "=?",
            onFocus: "=?",
            apptId: "=?",
            level: "=",
            allowEditTooth: "=",
            onRecordTooth: "=?",
            onSyncToothCode: "=?",
            onDeleteToothCode: "=?"
        },
        link: function(n) {
            var t = function(t) {
                    if (t > 0 && n.currentValue.splice(t, 1), angular.isDefined(n.onDeleteToothCode)) n.onDeleteToothCode({
                        index: t,
                        listName: "cureRecordList"
                    })
                },
                i = function() {
                    n.currentValue.push({
                        id: 0,
                        cure: "",
                        fdiToothCodesArray: []
                    })
                };
            (function() {
                n.addEMRControl = i;
                n.deleteEMRControl = t
            })()
        }
    }
}]);
emrModule.directive("emrDiagnoseRecordsEditView", ["$log", "$timeout", "$window", "$modal", "$q", "appNav", "loginContext", "practiceSvc", "schedulerUtil", "$sce", "systemConfigUtil", "printTemplateUtil", "constants", "patientUtil", "providerUtil", function() {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/emr/views/emr-components/edit/emr-diagnose-records-edit-view.html",
        scope: {
            field: "=",
            currentValue: "=?",
            isEmrCustomTemplateEnabled: "=?",
            onFocus: "=?",
            level: "=",
            allowEditTooth: "=?",
            onRecordTooth: "=?",
            onSyncToothCode: "=?",
            onDeleteToothCode: "=?"
        },
        link: function(n) {
            var t = function(t) {
                    if (t > 0 && n.currentValue.splice(t, 1), angular.isDefined(n.onDeleteToothCode)) n.onDeleteToothCode({
                        index: t,
                        listName: "diagnoseRecordList"
                    })
                },
                i = function() {
                    n.currentValue.push({
                        id: 0,
                        diagnose: "",
                        fdiToothCodesArray: []
                    })
                };
            (function() {
                n.addEMRControl = i;
                n.deleteEMRControl = t
            })()
        }
    }
}]);
emrModule.directive("emrFreeCheckboxEditView", [function() {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/emr/views/emr-components/edit/emr-free-checkbox-edit-view.html",
        scope: {
            currentValue: "=?",
            field: "="
        },
        link: function(n) {
            var t = function() {
                    var t = [],
                        i;
                    n.currentValue.fieldValue ? t = n.currentValue.fieldValue.split("|") : n.currentValue.fieldValue = n.field.defaultValue;
                    i = n.field.fieldValue ? n.field.fieldValue.split("|") : [];
                    n.options = _.map(i, function(n) {
                        return {
                            value: n,
                            isChecked: _.contains(t, n)
                        }
                    })
                },
                i = function(t, i) {
                    i.isChecked = t.target.checked;
                    var r = _.filter(n.options, function(n) {
                        return n.isChecked
                    });
                    n.currentValue.fieldValue = _.map(r, function(n) {
                        return n.value
                    }).join("|")
                };
            (function() {
                t();
                n.handleClick = i
            })()
        }
    }
}]);
emrModule.directive("emrFreeInputEditView", ["$log", "$timeout", "$window", "$modal", "$q", "emrCustomizeEditUtil", function(n, t, i, r, u, f) {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/emr/views/emr-components/edit/emr-free-input-edit-view.html",
        scope: {
            currentValue: "=?",
            field: "="
        },
        link: function(n) {
            var t = function() {
                n.currentValue.fieldValue || (n.currentValue.fieldValue = n.field.defaultValue);
                n.enableWhen = f.getEnableWhen(n.field, n.currentValue)
            };
            (function() {
                t()
            })()
        }
    }
}]);
emrModule.directive("emrFreeNamedPictureEditView", ["$log", "$timeout", "$window", "$modal", "$q", "appNav", "loginContext", "patientSvc", "aresNotification", "practiceSvc", "eventAggregator", "$sce", "systemConfigUtil", "emrCustomizeEditUtil", "constants", "patientUtil", "pictureSvc", function(n, t, i, r, u, f, e, o, s, h, c, l, a, v, y, p, w) {
    "use strict";
    return {
        restrict: "E",
        templateUrl: "/app/emr/views/emr-components/edit/emr-free-named-picture-edit-view.html",
        scope: {
            currentValue: "=?",
            field: "=",
            patientId: "=?"
        },
        link: function(n, i) {
            var r = function() {
                    n.currentValue.fieldValue || (n.currentValue.fieldValue = n.field.defaultValue);
                    i.find("#emr-photo-div").hover(function() {
                        var r = i.find(this);
                        r.hasClass("not-allow-action") || t(function() {
                            n.isEMRPhotoHovered = !0
                        })
                    }, function() {
                        var r = i.find(this);
                        r.hasClass("not-allow-action") || t(function() {
                            n.isEMRPhotoHovered = !1
                        })
                    })
                },
                u = function(t, i) {
                    var r = e.apiToken,
                        u = e.tokenType,
                        f = n.patientId || 0;
                    i.url = e.apiHost + "/api/v1/patient-photo?patientId=" + f;
                    i.headers = i.headers || {};
                    i.headers.Authorization = u + " " + r;
                    i.submit()
                },
                f = function() {},
                o = function() {},
                h = function(t, i) {
                    var r = parseInt(i.loaded / i.total * 100, 10);
                    n.progressBarPercentage = r + "%"
                },
                l = function(t, i) {
                    var r, u;
                    if (i.result != null && typeof i.result == "object") {
                        r = {};
                        for (u in i.result) r[u] = i.result[u];
                        r.type = "preview"
                    }
                    n.currentValue.picture = r;
                    n.currentValue.fieldValue = r.id;
                    n.progressBarPercentage = "0%"
                },
                a = function() {
                    n.progressBarPercentage = "0%";
                    s.error("文件上传失败！")
                },
                v = function() {
                    i.find(".picture-upload-panel").click()
                },
                y = function() {
                    return "/app/common/components/ares-photo/ares-upload-photo-item.html"
                },
                p = function() {
                    var t = n.currentValue ? n.currentValue.picture : null;
                    t && t.id && w.destroyPicture(t.id).success(function() {
                        n.currentValue.picture = {};
                        n.currentValue.fieldValue = null
                    })
                },
                b = function(n, t) {
                    var i = {
                        imgUrl: n.filePath,
                        type: "image",
                        width: "500",
                        height: "400"
                    };
                    c.publish(c.events.PopupFlyout, i, t.delegateTarget)
                };
            (function() {
                r();
                n.isEMRPhotoHovered = !1;
                n.uploadStart = f;
                n.uploadStop = o;
                n.uploadProgressed = h;
                n.uploadFinished = l;
                n.uploadFailed = a;
                n.addUpload = u;
                n.onClickFileDialog = v;
                n.buildImageTemplateUrl = y;
                n.deletePicture = p;
                n.showBigPicture = b
            })()
        }
    }
}]);
emrModule.directive("emrFreeNumberEditView", ["$log", "$timeout", "$window", "$modal", "$q", "appNav", "loginContext", "practiceSvc", "schedulerUtil", "$sce", "systemConfigUtil", "emrCustomizeEditUtil", "constants", "patientUtil", "providerUtil", function(n, t, i, r, u, f, e, o, s, h, c, l) {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/emr/views/emr-components/edit/emr-free-number-edit-view.html",
        scope: {
            currentValue: "=?",
            field: "="
        },
        link: function(n) {
            var t = function() {
                    n.currentValue.fieldValue || (n.currentValue.fieldValue = n.field.defaultValue);
                    n.optionData = n.field.optionData;
                    n.min = n.optionData && n.optionData.min ? n.optionData.min : 0;
                    n.max = n.optionData && n.optionData.max ? n.optionData.max : 999;
                    i();
                    n.enableWhen = l.getEnableWhen(n.field, n.currentValue)
                },
                i = function() {
                    var t = typeof n.currentValue.fieldValue;
                    t != "string" && t != "number" ? n.currentValue.fieldValue = n.min : t == "string" && (n.currentValue.fieldValue = n.currentValue.fieldValue ? parseFloat(n.currentValue.fieldValue) : n.min)
                };
            (function() {
                t()
            })()
        }
    }
}]);
emrModule.directive("emrFreePictureEditView", ["$log", "$timeout", "$window", "$modal", "$q", "appNav", "loginContext", "patientSvc", "aresNotification", "practiceSvc", "eventAggregator", "$sce", "systemConfigUtil", "emrCustomizeEditUtil", "constants", "patientUtil", "pictureSvc", function(n, t, i, r, u, f, e, o, s, h, c, l, a, v, y, p, w) {
    "use strict";
    return {
        restrict: "E",
        templateUrl: "/app/emr/views/emr-components/edit/emr-free-picture-edit-view.html",
        scope: {
            currentValue: "=?",
            field: "=",
            patientId: "=?"
        },
        link: function(n, i) {
            var r = function() {
                    n.currentValue.fieldValue || (n.currentValue.fieldValue = n.field.defaultValue);
                    i.find(".emr-photo").hover(function() {
                        var n = i.find(this);
                        n.hasClass("not-allow-action") || t(function() {
                            var t = n.find(".photo-action-wrap");
                            t.show()
                        })
                    }, function() {
                        var n = i.find(this);
                        n.hasClass("not-allow-action") || t(function() {
                            var t = n.find(".photo-action-wrap");
                            t.hide()
                        })
                    })
                },
                u = function(t, i) {
                    var r = e.apiToken,
                        u = e.tokenType,
                        f = n.patientId || 0;
                    i.url = e.apiHost + "/api/v1/patient-photo?patientId=" + f;
                    i.headers = i.headers || {};
                    i.headers.Authorization = u + " " + r;
                    i.submit()
                },
                f = function() {},
                o = function() {},
                h = function(t, i) {
                    var r = parseInt(i.loaded / i.total * 100, 10);
                    n.progressBarPercentage = r + "%"
                },
                l = function(t, i) {
                    var r, u;
                    if (i.result != null && typeof i.result == "object") {
                        r = {};
                        for (u in i.result) r[u] = i.result[u];
                        r.type = "preview"
                    }
                    n.currentValue.pictures || (n.currentValue.pictures = []);
                    n.currentValue.pictures.push(r);
                    n.currentValue.fieldValue = _(n.currentValue.pictures).pluck("id").join("|");
                    n.progressBarPercentage = "0%"
                },
                a = function() {
                    n.progressBarPercentage = "0%";
                    s.error("文件上传失败！")
                },
                v = function() {
                    i.find(".picture-upload-panel").click()
                },
                y = function() {
                    return "/app/common/components/ares-photo/ares-upload-photo-item.html"
                },
                p = function(t) {
                    t && t.id && w.destroyPicture(t.id).success(function() {
                        n.currentValue.pictures = _(n.currentValue.pictures).reject(function(n) {
                            return n.id == t.id
                        });
                        n.currentValue.fieldValue = _(n.currentValue.pictures).pluck("id").join("|")
                    })
                },
                b = function(n, t) {
                    var i = {
                        imgUrl: n.filePath,
                        type: "image",
                        width: "500",
                        height: "400"
                    };
                    c.publish(c.events.PopupFlyout, i, t.delegateTarget)
                };
            (function() {
                r();
                n.isEMRPhotoHovered = !1;
                n.uploadStart = f;
                n.uploadStop = o;
                n.uploadProgressed = h;
                n.uploadFinished = l;
                n.uploadFailed = a;
                n.addUpload = u;
                n.onClickFileDialog = v;
                n.buildImageTemplateUrl = y;
                n.deletePicture = p;
                n.showBigPicture = b
            })()
        }
    }
}]);
emrModule.directive("emrFreeRadioEditView", ["$log", "$timeout", "$window", "$modal", "$q", "appNav", "loginContext", "practiceSvc", "schedulerUtil", "$sce", "systemConfigUtil", "printTemplateUtil", "constants", "patientUtil", "providerUtil", function() {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/emr/views/emr-components/edit/emr-free-radio-edit-view.html",
        scope: {
            currentValue: "=?",
            field: "="
        },
        link: function(n) {
            var t = function() {
                n.currentValue.fieldValue || (n.currentValue.fieldValue = n.field.defaultValue);
                n.options = n.field.fieldValue ? n.field.fieldValue.split("|") : []
            };
            (function() {
                t()
            })()
        }
    }
}]);
emrModule.directive("emrFreeTextareaEditView", ["$log", "$timeout", "$window", "$modal", "$q", "emrCustomizeEditUtil", function(n, t, i, r, u, f) {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/emr/views/emr-components/edit/emr-free-textarea-edit-view.html",
        scope: {
            currentValue: "=?",
            field: "="
        },
        link: function(n) {
            var t = function() {
                n.currentValue.fieldValue || (n.currentValue.fieldValue = n.field.defaultValue);
                n.optionData = n.field.optionData;
                n.rows = n.optionData && n.optionData.rows ? n.optionData.rows : 2;
                n.enableWhen = f.getEnableWhen(n.field, n.currentValue)
            };
            (function() {
                t()
            })()
        }
    }
}]);
emrModule.directive("emrHistoryEditView", ["$log", "$timeout", "$window", "$modal", "$q", "appNav", "loginContext", "practiceSvc", "schedulerUtil", "$sce", "systemConfigUtil", "printTemplateUtil", "constants", "patientUtil", "providerUtil", function() {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/emr/views/emr-components/edit/emr-history-edit-view.html",
        scope: {
            field: "=",
            currentValue: "=?",
            isFirstVisit: "=?",
            onFocus: "=?",
            level: "="
        },
        link: function() {
            (function() {})()
        }
    }
}]);
emrModule.directive("emrOralCheckRecordsEditView", ["$log", "$timeout", "$window", "$modal", "$q", "appNav", "loginContext", "dataDicSvc", "generalExamSvc", "practiceSvc", "schedulerUtil", "$sce", "systemConfigUtil", "printTemplateUtil", "constants", "patientUtil", "providerUtil", "systemConfigSvc", function() {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        controller: "EmrOralCheckRecordsEditCtrl",
        templateUrl: "/app/emr/views/emr-components/edit/emr-oral-check-records-edit-view.html",
        scope: {
            field: "=",
            currentValue: "=?",
            isEmrCustomTemplateEnabled: "=?",
            onFocus: "=?",
            patientId: "=?",
            openTag: "=?",
            level: "=",
            allowEditTooth: "=",
            onRecordTooth: "=?",
            onExamImporting: "=?",
            onExamImported: "=?",
            onSyncToothCode: "=?",
            onDeleteToothCode: "=?",
            isShowToothSync: "="
        },
        link: function(n) {
            var t = function(t) {
                    if (t > 0 && n.currentValue.splice(t, 1), angular.isDefined(n.onDeleteToothCode)) n.onDeleteToothCode({
                        index: t,
                        listName: "oralCheckRecordList"
                    })
                },
                i = function() {
                    n.currentValue.push({
                        id: 0,
                        description: "",
                        observationName: "",
                        fdiToothCodesArray: [],
                        fdiToothCodes: ""
                    })
                },
                r = function(t, i) {
                    n.currentValue[i].description += " " + t.name + ", "
                },
                u = function(n, t, i, r) {
                    if (n.stopPropagation(), i && t.observationName) {
                        var u = t.observationName.split(",");
                        u.splice(r, 1);
                        t.observationName = u.join(",")
                    }
                },
                f = function(n) {
                    return n ? n.split(",") : []
                };
            (function() {
                n.addEMRControl = i;
                n.deleteEMRControl = t;
                n.onObservationSelected = r;
                n.removeItem = u;
                n.splitFn = f;
                n.IsAloneSaveOralCheckSymptom = n.$parent.IsAloneSaveOralCheckSymptom
            })()
        }
    }
}]);
emrModule.directive("emrPastHistoryEditView", ["$log", "$timeout", "$window", "$modal", "$q", "appNav", "loginContext", "practiceSvc", "schedulerUtil", "$sce", "systemConfigUtil", "printTemplateUtil", "constants", "patientUtil", "providerUtil", function() {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/emr/views/emr-components/edit/emr-past-history-edit-view.html",
        scope: {
            field: "=",
            currentValue: "=?",
            onFocus: "=?",
            level: "="
        },
        link: function() {
            (function() {})()
        }
    }
}]);
emrModule.directive("emrRadiologyCheckRecordsEditView", ["$log", "$timeout", "$window", "$modal", "$q", "appNav", "loginContext", "practiceSvc", "schedulerUtil", "$sce", "systemConfigUtil", "printTemplateUtil", "constants", "patientUtil", "providerUtil", function() {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/emr/views/emr-components/edit/emr-radiology-check-records-edit-view.html",
        scope: {
            field: "=",
            currentValue: "=?",
            isEmrCustomTemplateEnabled: "=?",
            onFocus: "=?",
            level: "=",
            allowEditTooth: "=",
            onRecordTooth: "=?",
            onSyncToothCode: "=?",
            onDeleteToothCode: "=?"
        },
        link: function(n) {
            var t = function(t) {
                    if (t > 0 && n.currentValue.splice(t, 1), angular.isDefined(n.onDeleteToothCode)) n.onDeleteToothCode({
                        index: t,
                        listName: "radiologyCheckRecordList"
                    })
                },
                i = function() {
                    n.currentValue.push({
                        id: 0,
                        description: "",
                        fdiToothCodesArray: []
                    })
                };
            (function() {
                n.addEMRControl = i;
                n.deleteEMRControl = t
            })()
        }
    }
}]);
emrModule.directive("emrTreatmentAdvicesEditView", ["$log", "$timeout", "$window", "$modal", "$q", "appNav", "loginContext", "practiceSvc", "schedulerUtil", "$sce", "systemConfigUtil", "printTemplateUtil", "constants", "patientUtil", "providerUtil", function() {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/emr/views/emr-components/edit/emr-treatment-advices-edit-view.html",
        scope: {
            field: "=",
            currentValue: "=?",
            onFocus: "=?",
            level: "=",
            allowEditTooth: "=",
            onRecordTooth: "=?",
            onSyncToothCode: "=?",
            onDeleteToothCode: "=?"
        },
        link: function(n) {
            var t = function(t) {
                    if (t > 0 && n.currentValue.splice(t, 1), angular.isDefined(n.onDeleteToothCode)) n.onDeleteToothCode({
                        index: t,
                        listName: "treatmentAdviceList"
                    })
                },
                i = function() {
                    n.currentValue.push({
                        id: 0,
                        content: "",
                        fdiToothCodesArray: []
                    })
                };
            (function() {
                n.addEMRControl = i;
                n.deleteEMRControl = t
            })()
        }
    }
}]);
emrModule.directive("emrTreatmentPlansEditView", ["$log", "$timeout", "$window", "$modal", "$q", "appNav", "loginContext", "patientSvc", "practiceSvc", "schedulerUtil", "$sce", "systemConfigUtil", "printTemplateUtil", "constants", "patientUtil", "providerUtil", function() {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        controller: "EmrTreatmentPlansEditCtrl",
        templateUrl: "/app/emr/views/emr-components/edit/emr-treatment-plans-edit-view.html",
        scope: {
            field: "=",
            currentValue: "=?",
            isEmrCustomTemplateEnabled: "=?",
            onFocus: "=?",
            patientId: "=?",
            level: "=",
            allowEditTooth: "=",
            onRecordTooth: "=?",
            onSyncToothCode: "=?",
            onDeleteToothCode: "=?"
        },
        link: function(n) {
            var t = function(t) {
                    if (t > 0 && n.currentValue.splice(t, 1), angular.isDefined(n.onDeleteToothCode)) n.onDeleteToothCode({
                        index: t,
                        listName: "treatmentPlanList"
                    })
                },
                i = function() {
                    n.currentValue.push({
                        id: 0,
                        planContent: "",
                        fdiToothCodesArray: []
                    })
                };
            (function() {
                n.addEMRControl = i;
                n.deleteEMRControl = t
            })()
        }
    }
}]);
emrModule.directive("emrMedicalImageChoicePictureDialogView", ["$timeout", function() {
    "use strict";
    return {
        templateUrl: "/app/emr/views/emr-components/edit/emr-medical-image-choice-picture-dialog/emr-medical-image-choice-picture-dialog-view.html",
        link: function(n, t) {
            n.selectAppoint = null;
            var i = null,
                r = function(i) {
                    t.find("#appointment-drop-down-list").kendoDropDownList({
                        dataSource: i,
                        dataTextField: "appointmentDescription",
                        dataValueField: "id",
                        value: i[0] ? i[0].id : null,
                        select: function(t) {
                            var i = this.dataItem(t.item);
                            i.id !== this.value() && i.id && (n.selectAppoint = i, n.getMedicalImageAppointmentList(i.id))
                        }
                    })
                },
                u = function() {
                    i || (n.selectAppoint && n.getMedicalImageAppointmentList(n.selectAppoint.id), i = setTimeout(function() {
                        clearTimeout(i);
                        i = null
                    }, 3e3))
                },
                f = function(t) {
                    t.target.checked ? _.each(n.pictures, function(t) {
                        t._isChecked = !0;
                        var i = _.find(n.selectPicture, function(n) {
                            return n.imageId === t.imageId
                        });
                        i ? i._isChecked = !0 : n.selectPicture.push(t)
                    }) : _.each(n.pictures, function(t) {
                        var i = _.find(n.selectPicture, function(n) {
                            return n.imageId === t.imageId
                        });
                        i ? i._isLock || (i._isChecked = !1) : n.selectPicture.push(t)
                    });
                    n.isAllChecked = t.target.checked
                };
            (function() {
                n.loadAllAppointments().then(function(t) {
                    t && t.length && (n.selectAppoint = t[0], n.getMedicalImageAppointmentList(t[0].id), r(t))
                });
                n.onRefresh = u;
                n.onCheckAll = f
            })()
        }
    }
}]);
emrModule.controller("EmrMedicalImageChoicePictureDialogCtrl", ["$scope", "$filter", "$q", "$sce", "$modalInstance", "host", "appointmentSvc", "constants", "imagingSvc", function(n, t, i, r, u, f, e, o, s) {
    "use strict";
    var c = t("toDateTimeString");
    n.pictures = [];
    n.sceControl = r.trustAsResourceUrl;
    var l = function() {
            n.selectPicture = f && f.imageList ? _.clone(f.imageList) : [];
            _.forEach(n.selectPicture, function(n) {
                n._isLock = n._isChecked = !0
            })
        },
        a = function() {
            var n = i.defer();
            return e.getSuperLiteAppointments(f.patientId).success(function(t) {
                t && _.forEach(t, function(n) {
                    n.appointmentDescription = c(n.startTime)
                });
                n.resolve(t)
            }), n.promise
        },
        v = function(t) {
            var r = i.defer();
            return s.getImagingListByAppointmentId(t).then(function(t) {
                if (t.data) {
                    var i = _.filter(t.data, function(n) {
                        return _.includes([1, 2, 3, 4, 5, 6, 7, 8], n.categoryId)
                    });
                    n.pictures = i.map(function(t) {
                        return n.selectAppoint && n.selectAppoint.startTime && (t.appointmentStartTimeStr = moment(n.selectAppoint.startTime).format("YYYY/MM/DD")), t.id && (t.imageId = t.id, delete t.id), t
                    });
                    _.forEach(n.pictures, function(t) {
                        var i, r;
                        f && f.imageList ? (i = _.find(f.imageList, {
                            imageId: t.imageId
                        }), t._isLock = t._isChecked = !!i, t._isLock && (r = _.find(n.selectPicture, function(n) {
                            return n.imageId === t.imageId
                        }), r || (i._isLock = t._isLock, i._isChecked = t._isChecked, n.selectPicture.push(i)))) : t._isLock = t._isChecked = !1
                    });
                    n.pictures.length > 0 && _.forEach(n.pictures, function(t) {
                        var i = _.find(n.selectPicture, function(n) {
                            return n.imageId === t.imageId
                        });
                        i && (t._isChecked = i._isChecked)
                    });
                    h()
                }
                r.resolve()
            }), r.promise
        },
        y = function() {
            var t = _.filter(n.selectPicture, function(n) {
                return n._isChecked
            });
            console.log("[emr-medical-image select picture]: ", n.selectPicture);
            u.close({
                action: "add",
                data: t
            })
        },
        p = function() {
            u.dismiss()
        },
        w = function(t) {
            var i = _.find(n.selectPicture, function(n) {
                return n.imageId === t.imageId
            });
            i ? i._isChecked = t._isChecked : n.selectPicture.push(t);
            h()
        },
        h = function() {
            var i = _.filter(n.pictures, function(n) {
                    return !n._isChecked
                }),
                t;
            i && i.length > 0 || n.pictures.length === 0 ? (n.isAllChecked = !1, n.isAllCheckedLock = !1) : (n.isAllChecked = !0, t = _.filter(n.pictures, function(n) {
                return !n._isLock
            }), n.isAllCheckedLock = t && t.length > 0 ? !1 : !0)
        };
    (function() {
        n.selectPicture = [];
        l();
        n.loadAllAppointments = a;
        n.getMedicalImageAppointmentList = v;
        n.onSave = y;
        n.onCancel = p;
        n.handleClick = w
    })()
}]);
emrModule.directive("emrMedicalImageEditView", ["$state", "$sce", "aresModalShelf", "eventAggregator", function(n, t, i, r) {
    "use strict";
    return {
        restrict: "E",
        templateUrl: "/app/emr/views/emr-components/edit/emr-medical-image-edit/emr-medical-image-edit-view.html",
        scope: {
            currentValue: "=?",
            field: "=",
            patientId: "=?"
        },
        link: function(u) {
            u.sceControl = t.trustAsResourceUrl;
            var f = function() {
                    u.currentValue ? _.forEach(u.currentValue, function(n) {
                        n.appointmentStartTime && !n.appointmentStartTimeStr && (n.appointmentStartTimeStr = moment(n.appointmentStartTime).format("YYYY/MM/DD"))
                    }) : u.currentValue = []
                },
                e = function() {
                    var t = i.open({
                        template: "<emr-medical-image-choice-picture-dialog-view><\/emr-medical-image-choice-picture-dialog-view>",
                        controller: "EmrMedicalImageChoicePictureDialogCtrl",
                        title: "关联影像",
                        resolve: {
                            host: function() {
                                return {
                                    imageList: u.currentValue,
                                    patientId: u.patientId
                                }
                            }
                        },
                        needActive: !0,
                        confirmClose: !1
                    });
                    t.result.then(function(t) {
                        t && t.action === "add" && (u.currentValue = _.map(t.data, function(t) {
                            return t.id = t.id ? t.id : 0, t.medicalRecordId = n.params.medicalRecordId > 0 ? Number(n.params.medicalRecordId) : 0, _.isUndefined(t.mgmtType) && (t.mgmtType = t.imageType === "dicom" ? 1 : 0), t.note = t.note ? t.note : "", t
                        }))
                    })
                },
                o = function(n, t) {
                    n && u.currentValue.splice(t, 1)
                },
                s = function(n, t) {
                    var i = {
                        imgUrl: n.mgmtType === 1 ? n.mediumUrl || n.mediumSizeImageUrl : n.fullImageUrl || n.fullUrl,
                        type: "image",
                        width: "500",
                        height: "300"
                    };
                    r.publish(r.events.PopupFlyout, i, t.delegateTarget)
                };
            (function() {
                f();
                u.addMedicalImage = e;
                u.onRevocation = o;
                u.showBigPicture = s
            })()
        }
    }
}]);
emrModule.directive("allMedicalrecordListView", ["$log", "$timeout", "$modal", "$q", "aresDialog", "$window", "$state", "appNav", "enums", "permissionProvider", "dataDicSvc", "patientSvc", "practiceSvc", "loginContext", "printUtil", "gridOptionUtil", "reportSvc", function(n, t, i, r, u, f, e, o, s, h, c, l, a, v, y, p, w) {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        controller: "allMedicalrecordCtrl",
        templateUrl: "/app/emr/views/medicalrecord-list/all-medicalrecord-list-view.html",
        scope: {
            officeId: "="
        },
        link: function(n, u) {
            var s = Ares.kendoGridUtil(f, n);
            u.find("#daysBeforeTodayInput").val() == "自定义" ? u.find(".isHideData").show() : u.find(".isHideData").hide();
            u.find("#daysBeforeTodayInput").change(function() {
                u.find("#daysBeforeTodayInput").val() == "自定义" ? u.find(".isHideData").show() : u.find(".isHideData").hide()
            });
            var l = function() {
                    var t = $(u).find("#MedicalrecordList"),
                        i, r;
                    t.html("");
                    i = t.offset().top;
                    r = $(window).height() - i - 10 - (window.Ares3 ? 20 : 0);
                    t.kendoGrid({
                        dataSource: {
                            transport: {
                                read: function(i) {
                                    if (n.isPageInit) {
                                        n.isPageInit = !1;
                                        t.data("kendoGrid").dataSource.query({
                                            page: n.pageIndex || 1,
                                            pageSize: n.pageSize || 10
                                        });
                                        i.success({
                                            data: [],
                                            total: 0
                                        });
                                        return
                                    }
                                    n.pageIndex = i.data.page || 1;
                                    n.pageSize = i.data.pageSize || 10;
                                    i.data.sort && i.data.sort.length > 0 ? (n.sortField = i.data.sort[0].field, n.sortRule = i.data.sort[0].dir) : (n.sortField = null, n.sortRule = null);
                                    n.search().then(function(n) {
                                        i.success(n)
                                    })
                                }
                            },
                            schema: {
                                data: "data",
                                total: "total"
                            },
                            pageSize: 10,
                            serverPaging: !0,
                            serverSorting: !0,
                            serverFiltering: !0
                        },
                        model: {
                            id: "id"
                        },
                        dataBound: k,
                        pageable: p.pageable,
                        scrollable: !0,
                        selectable: "single",
                        height: r,
                        sortable: !0,
                        columns: [{
                            field: "privateId",
                            title: "病历号",
                            width: "140px"
                        }, {
                            field: "patientName",
                            title: "姓名",
                            width: "130px"
                        }, {
                            field: "sexStr",
                            title: "性别",
                            width: "70px"
                        }, {
                            field: "age",
                            title: "年龄",
                            width: "70px"
                        }, {
                            field: "phoneNumber",
                            title: "联系电话",
                            width: "130px"
                        }, {
                            field: "mobile",
                            title: "手机",
                            width: "130px"
                        }, {
                            field: "department",
                            title: "医生科室",
                            width: "140px"
                        }, {
                            field: "doctorName",
                            title: "主治医生",
                            width: "120px"
                        }, {
                            field: "nurseName",
                            title: "助手",
                            width: "120px"
                        }, {
                            field: "recordCreatedTime",
                            title: "创建日期",
                            width: "180px"
                        }, {
                            field: "recordUpdatedTime",
                            title: "修改日期",
                            width: "180px"
                        }, {
                            field: "templateName",
                            title: "病历类型",
                            width: "120px"
                        }, {
                            field: "archive",
                            title: "病历归档",
                            width: "120px"
                        }, {
                            template: s.commandTemplate,
                            title: "",
                            width: "200px",
                            attributes: {
                                "class": "group-list"
                            },
                            locked: !0
                        }]
                    })
                },
                y = [{
                    text: "查看病历",
                    action: "goToMedical",
                    className: "custom-button btn-middle"
                }, {
                    text: "查看日志",
                    action: "changeLog",
                    className: "custom-button btn-middle"
                }, ],
                b = function() {
                    n.isAllowToReject && n.commands.unshift({
                        text: "打回",
                        action: "goToCorrectTask",
                        className: "custom-button btn-small"
                    })
                },
                k = function() {
                    var t = this;
                    n.isAllowToReject && $(u).find("#MedicalrecordList table tbody tr").each(function(n, i) {
                        var r = t.dataItem(i);
                        r.state === 2 ? ($('.btn-group button[data-action="goToCorrectTask"]', i).removeAttr("disabled"), $('.btn-group button[data-action="goToCorrectTask"]', i).text("打回")) : r.state === 1 && ($('.btn-group button[data-action="goToCorrectTask"]', i).attr("disabled", "true"), $('.btn-group button[data-action="goToCorrectTask"]', i).text("已打回"))
                    })
                },
                vt = function() {
                    var n = e.params.patientId;
                    n && t(function() {
                        ct(n)
                    }, 500)
                },
                d = function(t, i, r) {
                    var u = _.find(n.searchData.items, function(n) {
                        return n.id == r
                    });
                    n.$apply(function() {
                        switch (i) {
                            case "goToMedical":
                                o.goToEMR(u.patientId);
                                break;
                            case "changeLog":
                                tt(u.id);
                                break;
                            case "goToCorrectTask":
                                g(u.id)
                        }
                    })
                },
                g = function(t) {
                    nt(t).then(function() {
                        n.isPageInit = !0;
                        n.initGrid()
                    })
                },
                nt = function(n, t) {
                    var r = i.open({
                        animation: !0,
                        backdrop: "static",
                        controller: "MedicalrecordRejectionDialogCtrl",
                        template: "<medicalrecord-rejection-dialog-view><\/medicalrecord-rejection-dialog-view>",
                        windowClass: "small-dialog",
                        resolve: {
                            host: function() {
                                return {
                                    medicalRecordId: n,
                                    action: t
                                }
                            }
                        }
                    });
                    return r.result
                },
                tt = function(n) {
                    var t = i.open({
                        animation: !0,
                        backdrop: "static",
                        template: "<operation-log-list-view><\/operation-log-list-view>",
                        controller: "OperationLogListCtrl",
                        size: "lg",
                        windowClass: "operation-log-dialog",
                        resolve: {
                            host: function() {
                                return {
                                    id: n,
                                    type: "MedicalRecord"
                                }
                            }
                        }
                    })
                },
                v = function(t) {
                    c.doctorDic.loadActive().then(function(i) {
                        var u = angular.copy(i),
                            r;
                        n.doctors = rt(t, u);
                        r = {
                            id: -1,
                            name: "全部"
                        };
                        n.doctors.splice(0, 0, r);
                        it()
                    })
                },
                it = function() {
                    var i = u.find("#doctorInput"),
                        t;
                    i.kendoDropDownList({
                        dataSource: n.doctors,
                        placeholder: "",
                        dataTextField: "name",
                        dataValueField: "id",
                        select: function(t) {
                            var i = this.dataItem(t.item.index());
                            n.doctorId = i.id
                        }
                    });
                    t = i.data("kendoDropDownList");
                    localStorage.allMedicalrecord_doctorId ? (n.doctorId = localStorage.allMedicalrecord_doctorId, t.value(n.doctorId)) : t.value(-1)
                },
                rt = function(n, t) {
                    return !n || n === "全部" ? t : _.filter(t, function(t) {
                        return t.department === n
                    })
                },
                ut = function() {
                    c.departmentDic.loadActive().then(function(t) {
                        var i = {
                                itemName: "全部"
                            },
                            r, f;
                        t.splice(0, 0, i);
                        r = u.find("#departmentInput");
                        r.kendoDropDownList({
                            dataSource: t,
                            placeholder: "",
                            dataTextField: "itemName",
                            dataValueField: "itemName",
                            select: function(t) {
                                var i = this.dataItem(t.item.index());
                                n.department = i.itemName;
                                v(n.department)
                            }
                        });
                        f = r.data("kendoDropDownList");
                        localStorage.allMedicalrecord_department ? (n.department = localStorage.allMedicalrecord_department, f.value(n.department)) : (n.department = i.itemName, f.value(i.itemName))
                    })
                },
                ft = function() {
                    var n = [];
                    c.nurseDic.loadActive().then(function(t) {
                        angular.forEach(t, function(t) {
                            n.push(t)
                        });
                        c.assistantDic.loadActive().then(function(t) {
                            angular.forEach(t, function(t) {
                                n.push(t)
                            });
                            et(n)
                        })
                    })
                },
                et = function(t) {
                    var f = {
                            id: -1,
                            name: "全部"
                        },
                        i, r;
                    t.splice(0, 0, f);
                    i = u.find("#nurseInput");
                    i.kendoDropDownList({
                        dataSource: t,
                        placeholder: "",
                        dataTextField: "name",
                        dataValueField: "id",
                        select: function(t) {
                            var i = this.dataItem(t.item.index());
                            n.nurseId = i.id
                        }
                    });
                    r = i.data("kendoDropDownList");
                    localStorage.allMedicalrecord_nurseId ? (n.nurseId = localStorage.allMedicalrecord_nurseId, r.value(n.nurseId)) : r.value(f.id)
                },
                ot = function() {
                    a.getArchive().success(function(t) {
                        var i = t,
                            r, f;
                        i.splice(0, 0, {
                            id: -1,
                            itemName: "全部"
                        });
                        r = u.find("#archiveInput");
                        f = r.kendoDropDownList({
                            dataSource: i,
                            dataTextField: "itemName",
                            dataValueField: "itemName",
                            select: function(t) {
                                n.archive = this.dataItem(t.item)[this.options.dataValueField] || null
                            }
                        })
                    })
                },
                st = function() {
                    var t = r.defer();
                    return n.initLayoutTemplates().then(function() {
                        var i = n.layoutTemplates,
                            r = {
                                templateCode: "",
                                templateName: "全部"
                            };
                        i.splice(0, 0, r);
                        var f = u.find("#layoutTemplateInput"),
                            o = f.kendoDropDownList({
                                dataSource: i,
                                dataTextField: "templateName",
                                dataValueField: "templateCode",
                                select: function(t) {
                                    n.layoutTemplateCode = this.dataItem(t.item)[this.options.dataValueField] || null
                                }
                            }),
                            e = f.data("kendoDropDownList");
                        localStorage.allMedicalrecord_templateCode ? e.value(localStorage.allMedicalrecord_templateCode) : e.value(r.templateCode);
                        t.resolve()
                    }), t.promise
                },
                ht = function() {
                    var n = u.find("#layoutTemplateInput").data("kendoDropDownList");
                    return n ? n.value() : ""
                },
                ct = function(n) {
                    var t = u.find("#patientList"),
                        i = t.data("kendoGrid"),
                        f = i.dataSource,
                        e = f.get(n),
                        r = t.find("tbody>tr[data-uid=" + e.uid + "]");
                    r && i.select(r)
                },
                lt = function(n, t, i, r, f) {
                    u.find("#" + n + " #templateBody").css("margin", "" + t + "px " + i + "px " + r + "px " + f + "px")
                },
                at = function() {
                    var t = u.find("#MedicalrecordList").data("kendoGrid");
                    if (t) {
                        var i = t.columns,
                            r = n.getCriteria(),
                            f = {
                                criteria: r,
                                columns: i
                            };
                        w.exportMedicalRecord(f)
                    }
                };
            (function() {
                n.isAllowToReject = h.isAllowed("patientMedicalRecord.reject");
                n.exportData = at;
                n.commands = y;
                b();
                n.onCommandClick = d;
                n.templateListInit = lt;
                n.initGrid = l;
                n.doctors = [];
                n.getTemplateDropDownValue = ht;
                ut();
                v(n.department);
                ot();
                ft();
                st().then(function() {
                    t(function() {
                        n.isPageInit = !0;
                        l()
                    })
                });
                n.$on("$destroy", function() {
                    s.dispose()
                })
            })()
        }
    }
}]);
emrModule.directive("medicalrecordHomeView", ["$log", "$timeout", "$filter", "$window", "appNav", "enums", "permissionProvider", "aresModalShelf", "loginContext", "$state", function(n, t, i, r, u) {
    "use strict";
    return {
        restrict: "E",
        controller: "MedicalrecordHomeCtrl",
        templateUrl: "/app/emr/views/medicalrecord-list/medicalrecord-home-view.html",
        scope: {
            officeId: "=",
            isAll: "="
        },
        link: function(n) {
            var t = function() {
                    var t = [],
                        r;
                    t = n.isAll ? [new u.TabItem("medicalrecordCenter.allEMR", "全部病历", "icon-bag", "patientCenter.emrSearch")] : [new u.TabItem("pendingMedicalrecord.myEMR", "待办病历", "icon-note", null)];
                    n.states = t;
                    r = {
                        permissionCode: "setting.emrtemplate"
                    };
                    window.Ares3 && (n.commands = [new Ares.TabCommand("设置", i, "lc-btn lc-btn-primary", 0, r)])
                },
                i = function() {
                    u.goToState("systemSetting.medicalRecord")
                };
            (function() {
                t()
            })()
        }
    }
}]);
emrModule.directive("medicalrecordRejectionDialogView", ["$log", "$timeout", "$window", "aresDialog", function(n, t, i, r) {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/emr/views/medicalrecord-list/medicalrecord-rejection-dialog-view.html",
        link: function(n, i) {
            var u = function() {
                if (!n.taskObj && n.taskObj.rejectReason) {
                    r.info("提示", "打回病历任务需填写理由！");
                    return
                }
                if (n.taskObj.rejectReason.length > 500) {
                    r.info("提示", "理由不能超过500！");
                    return
                }
                n.save(n.taskObj)
            };
            (function() {
                n.onSave = u;
                t(function() {
                    Ares.centerModal(i.closest(".modal-dialog"))
                }, 5)
            })()
        }
    }
}]);
emrModule.directive("notwritingMedicalrecordDialogView", ["$log", "$timeout", "$window", "aresDialog", function(n, t, i, r) {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/emr/views/medicalrecord-list/notwriting-medicalrecord-dialog-view.html",
        link: function(n, i) {
            var u = function() {
                var t = i.find("#taskNotes").val();
                if (!t) {
                    r.info("提示", "忽略病历任务需填写备注！");
                    return
                }
                if (t && t.length > 500) {
                    r.info("提示", "内容长度不允许超过500！");
                    return
                }
                n.save(t)
            };
            (function() {
                n.onSave = u;
                t(function() {
                    Ares.centerModal(i.closest(".modal-dialog"))
                }, 5)
            })()
        }
    }
}]);
emrModule.directive("notwritingMedicalrecordListView", ["$log", "$timeout", "$modal", "$window", "$q", "localCache", "$state", "appNav", "dataDicSvc", "gridOptionUtil", "commonTaskSvc", "permissionProvider", function(n, t, i, r, u, f, e, o, s, h, c, l) {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        controller: "notwritingMedicalrecordCtrl",
        templateUrl: "/app/emr/views/medicalrecord-list/notwriting-medicalrecord-list-view.html",
        scope: {
            officeId: "="
        },
        link: function(n, a) {
            var k = f.getCache(f.keys.NotwritingMedicalrecordCriteria),
                v = null,
                y = Ares.kendoGridUtil(r, n);
            a.find("#daysBeforeTodayInput").val() == "自定义" ? a.find(".isHideData").show() : a.find(".isHideData").hide();
            a.find("#daysBeforeTodayInput").change(function() {
                a.find("#daysBeforeTodayInput").val() == "自定义" ? a.find(".isHideData").show() : a.find(".isHideData").hide()
            });
            var d = [{
                    text: "忽略",
                    action: "goToCancelTask",
                    className: "custom-button btn-small"
                }, {
                    text: "就诊记录",
                    action: "goToApptRecord",
                    className: "custom-button btn-middle"
                }, {
                    text: "病历记录",
                    action: "goToMedical",
                    className: "custom-button btn-middle"
                }, {
                    text: "创建病历",
                    action: "goToAddMedical",
                    className: "custom-button btn-middle"
                }, ],
                g = function() {
                    n.commands.unshift({
                        text: "整改",
                        action: "goToMedicalRecord",
                        className: "custom-button btn-small"
                    });
                    n.isAllowToReject && n.commands.unshift({
                        text: "打回",
                        action: "goToCorrectTask",
                        className: "custom-button btn-small"
                    })
                },
                nt = function() {
                    var t = this;
                    $(a).find("#MedicalrecordList table tbody tr").each(function(i, r) {
                        var u = t.dataItem(r),
                            f;
                        u.taskStatus == 1 ? $('.btn-group button[data-action="goToCancelTask"]', r).css("display", "none") : u.taskStatus == 2 && ($('.btn-group button[data-action="goToCancelTask"]', r).css("display", "none"), $('.btn-group button[data-action="goToAddMedical"]', r).css("display", "none"));
                        n.isAllowToReject && (u.taskStatus === 1 && u.taskType === 3 && u.state === 2 || u.taskStatus === 1 && u.taskType === 1 && u.state === 0 ? $('.btn-group button[data-action="goToCancelTask"]', r).css("display", "none") : $('.btn-group button[data-action="goToCorrectTask"]', r).css("display", "none"));
                        u.taskStatus === 0 && u.taskType === 3 && u.state === 1 ? $('.btn-group button[data-action="goToCancelTask"]', r).css("display", "none") : $('.btn-group button[data-action="goToMedicalRecord"]', r).css("display", "none");
                        f = Ares.today();
                        new Date(u.startTimeSource) < f && n.isStrongStrict && $('.btn-group button[data-action="goToAddMedical"]', r).css("display", "none")
                    })
                },
                kt = function() {
                    var n = e.params.patientId;
                    n && t(function() {
                        lt(n)
                    }, 500)
                },
                tt = function(t, i, r) {
                    if (n.searchResult && n.searchResult.items) {
                        var u = _.find(n.searchResult.items, function(n) {
                            return n.id == r
                        });
                        n.$apply(function() {
                            switch (i) {
                                case "goToMedical":
                                    rt(u.patientId);
                                    break;
                                case "goToApptRecord":
                                    ut(u.patientId);
                                    break;
                                case "goToCancelTask":
                                    it(u.id);
                                    break;
                                case "goToAddMedical":
                                    ft(u.patientId);
                                    break;
                                case "goToCorrectTask":
                                    ot(u.medicalRecordId);
                                    break;
                                case "goToMedicalRecord":
                                    et(u.patientId, u.medicalRecordId)
                            }
                        })
                    }
                },
                it = function(t) {
                    at(t).then(function() {
                        n.initGrid()
                    })
                },
                rt = function(n) {
                    o.goToEMR(n)
                },
                ut = function(n) {
                    o.goToApptRecord(n)
                },
                ft = function(n) {
                    o.goToEditEMR(n, {
                        patientId: n
                    })
                },
                et = function(n, t) {
                    o.goToEditEMR(n, {
                        patientId: n,
                        medicalRecordId: t
                    })
                },
                ot = function(t) {
                    w(t).then(function() {
                        n.initGrid()
                    })
                },
                st = function() {
                    s.departmentDic.loadActive().then(function(t) {
                        var i = {
                                itemName: "全部"
                            },
                            r, u;
                        t.splice(0, 0, i);
                        r = a.find("#departmentInput");
                        r.kendoDropDownList({
                            dataSource: t,
                            placeholder: "",
                            dataTextField: "itemName",
                            dataValueField: "itemName",
                            select: function(t) {
                                var i = this.dataItem(t.item.index());
                                n.department = i.itemName;
                                p(n.department)
                            }
                        });
                        u = r.data("kendoDropDownList");
                        v.nowritingemr_department ? (n.department = v.nowritingemr_department, u.value(n.department)) : (n.department = i.itemName, u.value(i.itemName))
                    })
                },
                p = function(t) {
                    s.doctorDic.loadActive().then(function(i) {
                        var u = angular.copy(i),
                            r;
                        n.doctors = ht(t, u);
                        r = {
                            id: -1,
                            name: "全部"
                        };
                        n.doctors.splice(0, 0, r);
                        ct()
                    })
                },
                ht = function(n, t) {
                    return !n || n === "全部" ? t : _.filter(t, function(t) {
                        return t.department === n
                    })
                },
                ct = function() {
                    var i = a.find("#doctorInput"),
                        t;
                    i.kendoDropDownList({
                        dataSource: n.doctors,
                        placeholder: "",
                        dataTextField: "name",
                        dataValueField: "id",
                        select: function(t) {
                            var i = this.dataItem(t.item.index());
                            n.doctorId = i.id
                        }
                    });
                    t = i.data("kendoDropDownList");
                    v.nowritingemr_doctorId ? (n.doctorId = v.nowritingemr_doctorId, t.value(n.doctorId)) : t.value(-1)
                },
                dt = function() {
                    var t = $("#MedicalrecordList"),
                        i = t.data("kendoGrid");
                    i.dataSource.data(n.searchResult)
                },
                lt = function(n) {
                    var t = $(a).find("#patientList"),
                        i = t.data("kendoGrid"),
                        u = i.dataSource,
                        f = u.get(n),
                        r = t.find("tbody>tr[data-uid=" + f.uid + "]");
                    r && i.select(r)
                },
                at = function(n) {
                    var t = i.open({
                        animation: !0,
                        backdrop: "static",
                        controller: "NotwritingMedicalrecordDialogCtrl",
                        template: "<notwriting-medicalrecord-dialog-view><\/notwriting-medicalrecord-dialog-view>",
                        size: "lg",
                        windowClass: "small-dialog",
                        resolve: {
                            host: function() {
                                return {
                                    taskId: n
                                }
                            }
                        }
                    });
                    return t.result
                },
                w = function(n, t) {
                    var r = i.open({
                        animation: !0,
                        backdrop: "static",
                        controller: "MedicalrecordRejectionDialogCtrl",
                        template: "<medicalrecord-rejection-dialog-view><\/medicalrecord-rejection-dialog-view>",
                        windowClass: "small-dialog",
                        resolve: {
                            host: function() {
                                return {
                                    medicalRecordId: n,
                                    action: t
                                }
                            }
                        }
                    });
                    return r.result
                },
                vt = function() {
                    var i = a.find("#medicalRecordStatus"),
                        t = [{
                            id: -1,
                            name: "全部"
                        }, {
                            id: 0,
                            name: "未写"
                        }, {
                            id: 1,
                            name: "已写"
                        }, {
                            id: 2,
                            name: "已忽略"
                        }],
                        r;
                    t.push({
                        id: 10,
                        name: "待整改"
                    });
                    t.push({
                        id: 11,
                        name: "已整改"
                    });
                    i.kendoDropDownList({
                        dataSource: t,
                        dataTextField: "name",
                        dataValueField: "id",
                        height: 230,
                        select: function(t) {
                            n.medicalRecordStatus = this.dataItem(t.item)[this.options.dataValueField]
                        }
                    });
                    r = i.data("kendoDropDownList");
                    n.medicalRecordStatus = v.nowritingemr_medicalRecordStatus;
                    r.value(n.medicalRecordStatus)
                },
                yt = function() {
                    var t = u.defer();
                    return n.initLayoutTemplates().then(function() {
                        var i = n.layoutTemplates,
                            r = {
                                templateCode: "",
                                templateName: "全部"
                            };
                        i.splice(0, 0, r);
                        var u = a.find("#layoutTemplateInput"),
                            e = u.kendoDropDownList({
                                dataSource: i,
                                dataTextField: "templateName",
                                dataValueField: "templateCode",
                                select: function(t) {
                                    n.layoutTemplateCode = this.dataItem(t.item)[this.options.dataValueField] || null
                                }
                            }),
                            f = u.data("kendoDropDownList");
                        v.nowritingemr_templateCode ? f.value(v.nowritingemr_templateCode) : f.value(r.templateCode);
                        t.resolve()
                    }), t.promise
                },
                pt = function() {
                    var n = a.find("#layoutTemplateInput").data("kendoDropDownList");
                    return n ? n.value() : ""
                },
                b = function() {
                    var t = $(a).find("#MedicalrecordList");
                    t.html("");
                    var i = t.offset().top,
                        r = $(window).height() - i - 10 - (window.Ares3 ? 20 : 0),
                        u = t.kendoGrid({
                            dataSource: {
                                transport: {
                                    read: function(t) {
                                        n.pageIndex = t.data.page || 1;
                                        n.pageSize = t.data.pageSize || 10;
                                        n.searchMedicalRecords().then(function(n) {
                                            t.success(n)
                                        })
                                    }
                                },
                                schema: {
                                    data: "items",
                                    total: "totalCount"
                                },
                                pageSize: 10,
                                serverPaging: !0,
                                serverFiltering: !0
                            },
                            model: {
                                id: "id"
                            },
                            pageable: h.pageable,
                            dataBound: nt,
                            scrollable: !0,
                            selectable: "single",
                            height: r,
                            sortable: !0,
                            columns: [{
                                field: "privateId",
                                title: "病历号",
                                width: "120px"
                            }, {
                                field: "name",
                                title: "姓名",
                                width: "120px"
                            }, {
                                field: "sexStr",
                                title: "性别",
                                width: "70px"
                            }, {
                                field: "age",
                                title: "年龄",
                                width: "70px"
                            }, {
                                field: "phoneNumber",
                                title: "联系电话",
                                width: "120px"
                            }, {
                                field: "mobile",
                                title: "手机",
                                width: "120px"
                            }, {
                                field: "department",
                                title: "医生科室",
                                width: "120px"
                            }, {
                                field: "doctorName",
                                title: "预约医生",
                                width: "100px"
                            }, {
                                field: "startTime",
                                title: "预约时间",
                                width: "180px"
                            }, {
                                field: "checkInType",
                                title: "就诊类型",
                                width: "100px"
                            }, {
                                field: "layoutTemplateName",
                                title: "病历类型",
                                width: "120px"
                            }, {
                                field: "taskStatusStr",
                                title: "病历状态",
                                width: "160px",
                                template: function(n) {
                                    var t = '<span class="enyo-text-primary">' + n.taskStatusStr + "<\/span>";
                                    return n.taskType === 3 && (t = '<span class="enyo-text-primary" style="color: #F7871D;">' + n.taskStatusStr + '<\/span><a class="reject-dialog" style="margin-left: 6px;" dataId=' + n.medicalRecordId + ">查看原因<\/a>"), t
                                }
                            }, {
                                hidden: !n.isDelunCustomFeatureOpen,
                                field: "apptConsultStateStr",
                                title: "是否成交",
                                width: "60px"
                            }, {
                                field: "notes",
                                title: "备注",
                                width: "250px",
                                attributes: {
                                    "class": "wrap-promt"
                                }
                            }, {
                                template: y.commandTemplate,
                                title: "",
                                width: "300px",
                                attributes: {
                                    "class": "group-list"
                                },
                                locked: !0
                            }]
                        }).data("kendoGrid");
                    u.table.on("click", ".reject-dialog", wt)
                },
                wt = function() {
                    var n = $(this).attr("dataId");
                    w(n, "readonly")
                },
                bt = function() {
                    var t = a.find("#MedicalrecordList").data("kendoGrid");
                    if (t) {
                        var i = t.columns,
                            r = n.getSearchCriteria(),
                            u = {
                                criteria: r,
                                columns: i
                            };
                        c.exportNotWritingMedicalrecord(u)
                    }
                };
            (function() {
                n.exportMedicalrecord = bt;
                n.isAllowToReject = l.isAllowed("patientMedicalRecord.reject");
                n.commands = d;
                g();
                n.onCommandClick = tt;
                n.initGrid = b;
                n.doctors = [];
                n.getTemplateDropDownValue = pt;
                v = k.loadObject();
                n.doctors = [];
                st();
                p(n.department);
                n.initSearchCriteria(v);
                vt();
                yt().then(function() {
                    t(function() {
                        b()
                    })
                });
                n.$on("$destroy", function() {
                    y.dispose()
                })
            })()
        }
    }
}]);